今天呢主要對(duì)pyMySQL模塊進(jìn)行使用講解一下:
創(chuàng)新互聯(lián)是一家專業(yè)提供靈壽企業(yè)網(wǎng)站建設(shè),專注與網(wǎng)站設(shè)計(jì)、成都網(wǎng)站設(shè)計(jì)、H5頁(yè)面制作、小程序制作等業(yè)務(wù)。10年已為靈壽眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)站設(shè)計(jì)公司優(yōu)惠進(jìn)行中。
https://www.cnblogs.com/lilidun/p/6041198.html
Linux系統(tǒng)上安裝pip3通過(guò)這個(gè)文檔查看
查詢操作:
importpymysql
db = pymysql.connect(host="localhost",user="root",password="",db="lxf",port=3306)
# 使用cursor()獲取操作游標(biāo)
cur = db.cursor()
#查詢操作
sql ="select* from user"
try:
cur.execute(sql) # 執(zhí)行sql語(yǔ)句
results = cur.fetchall() # 獲取查詢的所有記錄
print("id","name","password")
# 遍歷結(jié)果
forrowinresults:
id = row[0]
name = row[1]
password = row[2]
print(id,name,password)
exceptExceptionase:
raisee
finally:
db.close()#關(guān)閉連接
插入數(shù)據(jù):
importpymysql
db = pymysql.connect(host='localhost',user='root',password='',db='lxf',port=3306)
cur = db.cursor()
#插入操作
sql_insert ="""insert into user(id,name,pwd) values(5,'liu','123')"""
try:
cur.execute(sql_insert)
# 提交
db.commit()
exceptExceptionase:
# 錯(cuò)誤回滾
db.rollback()
finally:
db.close()
更新操作:
importpymysql
# 3.更新操作
db = pymysql.connect(host="localhost",user="root",
password="",db="lxf",port=3306)
# 使用cursor()方法獲取操作游標(biāo)
cur = db.cursor()
sql_update ="update user set name = '%s' where id = %d"
try:
cur.execute(sql_update % ("lxf",1)) # 像sql語(yǔ)句傳遞參數(shù)
# 提交
db.commit()
exceptExceptionase:
# 錯(cuò)誤回滾
db.rollback()
finally:
db.close()
刪除操作:
importpymysql
db = pymysql.connect(host='localhost',user='root',password='',db='lxf',port=3306)
#使用游標(biāo)
cur = db.cursor()
sql_delete="delete from user where id = %d"
try:
cur.execute(sql_delete %(1))#傳遞參數(shù)
#提交
db.commit()
exceptExceptionase:
#錯(cuò)誤回滾
db.rollback()
finally:
db.close()
數(shù)據(jù)庫(kù)備份:
#!/usr/bin/env python
import pymysql
import os
import time
TIME =time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
connect = pymysql.connect(host='localhost',user='root',password='123456',db='test',port=3306)
conn = connect.cursor()
os.system("""mysqldump -uroot -p123456 test > /root/test.sql""")
其實(shí)這里只是一個(gè)簡(jiǎn)單的備份,還可以加上time模塊備份每一天有日期,另外還可以加上hash模塊對(duì)密碼進(jìn)行加密,如果要想了解這兩個(gè)模塊的用發(fā)可以看看我的python分類中有相關(guān)的操作
新聞名稱:pymysql模塊對(duì)數(shù)據(jù)庫(kù)的操作與備份
標(biāo)題網(wǎng)址:http://chinadenli.net/article36/gphhpg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信小程序、品牌網(wǎng)站設(shè)計(jì)、ChatGPT、用戶體驗(yàn)、網(wǎng)站策劃、動(dòng)態(tài)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)