Python pymysql操作MySQL詳細
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詳細的文章就介紹到這了,更多相關(guān)Python pymysql操作MySQL內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
在Python中使用defaultdict初始化字典以及應(yīng)用方法
今天小編就為大家分享一篇在Python中使用defaultdict初始化字典以及應(yīng)用方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-10-10
Python+pyplot繪制帶文本標(biāo)注的柱狀圖方法
今天小編就為大家分享一篇Python+pyplot繪制帶文本標(biāo)注的柱狀圖方法,具有很好的價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07
Python基于numpy靈活定義神經(jīng)網(wǎng)絡(luò)結(jié)構(gòu)的方法
這篇文章主要介紹了Python基于numpy靈活定義神經(jīng)網(wǎng)絡(luò)結(jié)構(gòu)的方法,結(jié)合實例形式分析了神經(jīng)網(wǎng)絡(luò)結(jié)構(gòu)的原理及Python具體實現(xiàn)方法,涉及Python使用numpy擴展進行數(shù)學(xué)運算的相關(guān)操作技巧,需要的朋友可以參考下2017-08-08
Python 使用folium繪制leaflet地圖的實現(xiàn)方法
今天小編就為大家分享一篇Python 使用folium繪制leaflet地圖的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-07-07

