封裝一個python的pymysql操作類
更新時間:2022年12月25日 09:13:36 作者:野生大蝦
這篇文章主要介紹了封裝一個python的pymysql操作類的相關資料,需要的朋友可以參考下
最近使用pymysql寫腳本的情況越來越多了,剛好整理,簡單封裝一個pymysql的操作類
import pymysql
class MysqlDB:
def __init__(
self,
host=None,
port=None,
db=None,
account=None,
password=None,
connect_timeout=20,
read_timeout=20,
write_timeout=20
):
self.conn = pymysql.connect(
host=self.host,
port=self.port,
db=self.db,
user=self.account,
passwd=self.password,
connect_timeout=self.connect_timeout,
read_timeout=self.read_timeout,
write_timeout=self.write_timeout
)
def fetch(self, table_name=None, fields=(), where=None, many=False):
cur = self.conn.cursor()
if where:
sql = f'select {",".join(fields)} from {table_name} where {where}'
else:
sql = f'select {",".join(fields)} from {table_name}'
cur.execute(sql)
if many:
data = cur.fetchmany()
else:
data = cur.fetchone()
cur.close()
return data
def update(self, table_name=None, field=None, value=None, where=None):
cur = self.conn.cursor()
sql = f'update {table_name} set {field} = {value}'
if where:
sql += f'where {where}'
cur.execute(sql)
self.conn.commit()
cur.close()
def insert(self, table_name=None, single=True, data_list: list = []):
cur = self.conn.cursor()
for data in data_list:
sql = f'insert into {table_name}({",".join([key for key in data.keys()])}) values({",".join(["%s" for _ in range(len(data.keys()))])})'
cur.execute(sql, data)
self.conn.commit()
cur.close()
def quit(self):
self.conn.close()到此這篇關于封裝一個python的pymysql操作類的文章就介紹到這了,更多相關封裝pymysql操作類內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python?PaddleGAN實現(xiàn)照片人物性別反轉
PaddleGAN中的styleganv2editing.py是支持性別編輯的。所以本文將介紹如何通過調整參數,來試著實現(xiàn)一下照片的性別翻轉。感興趣的小伙伴可以學習一下2021-12-12
在linux系統(tǒng)中安裝python3.8.1?并卸載?python3.6.2?更新python3引導到3.8.1的
這篇文章主要介紹了如何在linux系統(tǒng)中安裝python3.8.1?并卸載?python3.6.2?更新python3引導到3.8.1,本文分步驟給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-11-11
Python字符串格式化f-string多種功能實現(xiàn)
這篇文章主要介紹了Python字符串格式化f-string格式多種功能實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-05-05

