封裝一個python的pymysql操作類
更新時間:2022年12月25日 09:13:36 作者:野生大蝦
這篇文章主要介紹了封裝一個python的pymysql操作類的相關(guān)資料,需要的朋友可以參考下
最近使用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實(shí)現(xiàn)套接字創(chuàng)建
這篇文章主要為大家介紹了python套接字創(chuàng)建實(shí)現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05Python傳統(tǒng)圖像處理之皮膚區(qū)域檢測詳解
這篇文章主要介紹了在不同情景下對傳統(tǒng)圖像進(jìn)行皮膚區(qū)域檢測,文章中的代碼具有一定的參考價值,感興趣的小伙伴可以跟隨小編一起來學(xué)習(xí)學(xué)習(xí)2021-12-12Python學(xué)習(xí)筆記之文件的讀寫操作實(shí)例分析
這篇文章主要介紹了Python學(xué)習(xí)筆記之文件的讀寫操作,結(jié)合實(shí)例形式詳細(xì)分析了Python常見的文件讀寫操作實(shí)現(xiàn)技巧及相關(guān)注意事項(xiàng),需要的朋友可以參考下2019-08-08python tkinter實(shí)現(xiàn)界面切換的示例代碼
今天小編就為大家分享一篇python tkinter實(shí)現(xiàn)界面切換的示例代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06關(guān)于Python的一些學(xué)習(xí)總結(jié)
這篇文章主要介紹了關(guān)于Python的一些總結(jié),希望自己以后在學(xué)習(xí)Python的過程中可以邊學(xué)習(xí)邊總結(jié),就自己之前的學(xué)習(xí)先做以總結(jié),之后將不斷總結(jié)更新2018-05-05