pymysql模塊對數(shù)據(jù)庫的操作與備份

今天呢主要對pyMySQL模塊進行使用講解一下:

創(chuàng)新互聯(lián)是一家專業(yè)提供靈壽企業(yè)網站建設,專注與網站設計、成都網站設計、H5頁面制作、小程序制作等業(yè)務。10年已為靈壽眾多企業(yè)、政府機構等服務。創(chuàng)新互聯(lián)專業(yè)網站設計公司優(yōu)惠進行中。

https://www.cnblogs.com/lilidun/p/6041198.html

Linux系統(tǒng)上安裝pip3通過這個文檔查看

 

查詢操作:

 

 

 

importpymysql

db = pymysql.connect(host="localhost",user="root",password="",db="lxf",port=3306)
# 使用cursor()獲取操作游標
cur = db.cursor()

#查詢操作
sql ="select* from user"

try:
    cur.execute(sql)  # 執(zhí)行sql語句

    results = cur.fetchall()  # 獲取查詢的所有記錄
    print("id","name","password")
    # 遍歷結果
    forrowinresults:
        id = row[0]
        name = row[1]
        password = row[2]
        print(id,name,password)
exceptExceptionase:
    raisee
finally:
    db.close()#關閉連接

 

 pymysql模塊對數(shù)據(jù)庫的操作與備份

插入數(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:
    # 錯誤回滾
    db.rollback()
finally:
    db.close()

 

 pymysql模塊對數(shù)據(jù)庫的操作與備份

更新操作:

 

importpymysql

# 3.更新操作
db = pymysql.connect(host="localhost",user="root",
                     password="",db="lxf",port=3306)

# 使用cursor()方法獲取操作游標
cur = db.cursor()

sql_update ="update user set name = '%s' where id = %d"

try:
    cur.execute(sql_update % ("lxf",1))  # 像sql語句傳遞參數(shù)
    # 提交
    db.commit()
exceptExceptionase:
    # 錯誤回滾
    db.rollback()
finally:
    db.close()

 

 



 pymysql模塊對數(shù)據(jù)庫的操作與備份

 

刪除操作:

 

 

importpymysql
db = pymysql.connect(host='localhost',user='root',password='',db='lxf',port=3306)
#使用游標
cur = db.cursor()

sql_delete="delete from user where id = %d"
try:
    cur.execute(sql_delete %(1))#傳遞參數(shù)
    #提交
    db.commit()
exceptExceptionase:
    #錯誤回滾
    db.rollback()
finally:
    db.close()

 

 pymysql模塊對數(shù)據(jù)庫的操作與備份

 

數(shù)據(jù)庫備份:

 pymysql模塊對數(shù)據(jù)庫的操作與備份

#!/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""")

pymysql模塊對數(shù)據(jù)庫的操作與備份

 

 其實這里只是一個簡單的備份,還可以加上time模塊備份每一天有日期,另外還可以加上hash模塊對密碼進行加密,如果要想了解這兩個模塊的用發(fā)可以看看我的python分類中有相關的操作

新聞名稱:pymysql模塊對數(shù)據(jù)庫的操作與備份
標題網址:http://muchs.cn/article36/gphhpg.html

成都網站建設公司_創(chuàng)新互聯(lián),為您提供微信小程序、品牌網站設計ChatGPT、用戶體驗、網站策劃、動態(tài)網站

廣告

聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

手機網站建設