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)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python飛機(jī)大戰(zhàn)游戲?qū)嵗v解
在本篇文章里小編給大家整理的是一篇關(guān)于python飛機(jī)大戰(zhàn)游戲?qū)嵗v解,有興趣的朋友們可以參考下。2020-12-12
使用Python進(jìn)行體育競技分析(預(yù)測球隊成績)
這篇文章主要介紹了用Python進(jìn)行體育競技分析(預(yù)測球隊成績),本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-05-05
PyTorch 遷移學(xué)習(xí)實踐(幾分鐘即可訓(xùn)練好自己的模型)
這篇文章主要介紹了PyTorch 遷移學(xué)習(xí)實踐(幾分鐘即可訓(xùn)練好自己的模型),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
python連接kafka加載數(shù)據(jù)的項目實踐
本文主要介紹了python連接kafka加載數(shù)據(jù)的項目實踐,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05

