封裝一個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()到此這篇關(guān)于封裝一個python的pymysql操作類的文章就介紹到這了,更多相關(guān)封裝pymysql操作類內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python?PaddleGAN實現(xiàn)照片人物性別反轉(zhuǎn)
PaddleGAN中的styleganv2editing.py是支持性別編輯的。所以本文將介紹如何通過調(diào)整參數(shù),來試著實現(xiàn)一下照片的性別翻轉(zhuǎn)。感興趣的小伙伴可以學習一下2021-12-12
基于Python+Pyqt5開發(fā)一個應(yīng)用程序
今天給大家?guī)淼氖顷P(guān)于Python的相關(guān)知識,文章圍繞著Python+Pyqt5開發(fā)一個應(yīng)用程序展開,文中有非常詳細的介紹及代碼示例,需要的朋友可以參考下2021-06-06
PyTorch中關(guān)于tensor.repeat()的使用
這篇文章主要介紹了PyTorch中關(guān)于tensor.repeat()的使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11
在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解析Chrome瀏覽器歷史瀏覽記錄和收藏夾數(shù)據(jù)
大家好,本篇文章主要講的是python解析Chrome瀏覽器歷史瀏覽記錄和收藏夾數(shù)據(jù),感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下2022-02-02
Python字符串格式化f-string多種功能實現(xiàn)
這篇文章主要介紹了Python字符串格式化f-string格式多種功能實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-05-05

