Python pymysql操作MySQL詳細
更新時間:2021年09月26日 15:13:20 作者:tigeriaf
pymysql是Python3.x中操作MySQL數據庫的模塊,其兼容于MySQLdb,使用方法也與MySQLdb幾乎相同,但是性能不如MySQLdb,但是由于其安裝使用方便、對中文兼容性也更好等優(yōu)點,被廣泛使用??梢允褂胮ip install pymysql進行安裝。
1、使用
1.1 簡單使用
import pymysql
# 創(chuàng)建連接
con = pymysql.connect(
host='localhost',
port=3306,
user='root',
password='123456',
database='test',
charset='utf8'
)
# 創(chuàng)建游標
cursor = con.cursor()
# 執(zhí)行新增SQL,返回受影響行數
row1 = cursor.execute("insert into user (username, password) values ('username3','password3')")
print(row1)
# 執(zhí)行更新SQL,返回受影響行數
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])
# 提交,不然無法保存新增或者更新的數據
con.commit()
# 關閉游標
cursor.close()
# 關閉連接
con.close()
注意:數據庫表中存在中文時,創(chuàng)建連接需要指定charset='utf8',否則中文顯示會亂碼。 其中cursor.fetchall()是獲取所有結果集,如果只有一條結果集,可以使用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):
"""
關閉鏈接
"""
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;")
到此這篇關于Python pymysql操作MySQL詳細的文章就介紹到這了,更多相關Python pymysql操作MySQL內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

