Python pymysql操作MySQL詳細(xì)
1、使用
1.1 簡單使用
import pymysql
# 創(chuàng)建連接
con = pymysql.connect(host='localhost',port=3306,user='root',password='123456',database='test',charset='utf8'
)
# 創(chuàng)建游標(biāo)
cursor = con.cursor()
# 執(zhí)行新增SQL,返回受影響行數(shù)
row1 = cursor.execute("insert into user (username, password) values ('username3','password3')")
print(row1)
# 執(zhí)行更新SQL,返回受影響行數(shù)
row2 = cursor.execute("update user set password = '123456' where id > 2;")
# 執(zhí)行查詢SQL
res = cursor.execute("SELECT * FROM user;")
result = cursor.fetchall()
for info in result:
print(info[0], info[1])
# 提交,不然無法保存新增或者更新的數(shù)據(jù)
con.commit()
# 關(guān)閉游標(biāo)
cursor.close()
# 關(guān)閉連接
con.close()
注意:數(shù)據(jù)庫表中存在中文時,創(chuàng)建連接需要指定charset='utf8',否則中文顯示會亂碼。 其中cursor.fetchall()是獲取所有結(jié)果集,如果只有一條結(jié)果集,可以使用cursor.fetchone() 。
1.2 封裝工具類
為了使用方便,可以直接封裝成工具類:
import pymysql class MysqlHelper: def __init__(self, config): self.host = config["host"] self.port = config["port"] self.user = config["user"] self.password = config["password"] self.db = config["db"] self.charset = config["charset"] self.con = None self.cursor = None def create_con(self): """ 創(chuàng)建連接 """ try: self.con = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password, database=self.db, charset='utf8') self.cursor = self.con.cursor() return True except Exception as e: print(e) return False # def close_con(self): """ 關(guān)閉鏈接 """ if self.cursor: self.cursor.close() if self.con: self.con.close() # sql執(zhí)行 def execute_sql(self, sql): """ 執(zhí)行插入/更新/刪除語句 """ try: self.create_con() print(sql) self.cursor.execute(sql) self.con.commit() except Exception as e: print(e) finally: self.close_con() def select(self, sql, *args): """ 執(zhí)行查詢語句 """ try: self.create_con() print(sql) self.cursor.execute(sql, args) res = self.cursor.fetchall() return res except Exception as e: print(e) return False finally: self.close_con()
使用工具類:
config = {
"host": 'localhost',
"port": 3306,
"user": 'root',
"password": '123456',
"db": 'test',
"charset": 'utf8'
}
db = MysqlHelper(config)
db.execute_sql("insert into user (username, password) values ('username4','password4')")
db.select("SELECT * FROM user;")
到此這篇關(guān)于Python pymysql操作MySQL詳細(xì)的文章就介紹到這了,更多相關(guān)Python pymysql操作MySQL內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信