pymysql模块对数据库的操作与备份

今天呢主要对pymysql模块进行使用讲解一下:

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

Linux系统上安装pip3通过这个文档查看

 

查询操作:

 

 

 

import pymysql

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

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

try:
    cur.execute(sql)  # 执行sql语句

    results = cur.fetchall()  # 获取查询的所有记录
    print("id", "name", "password")
    # 遍历结果
    for row in results:
        id = row[0]
        name = row[1]
        password = row[2]
        print(id, name, password)
except Exception as e:
    raise e
finally:
    db.close() #关闭连接

 

 图片1.png

扫描二维码关注公众号,回复: 2527177 查看本文章

插入数据:

 

 

import pymysql
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()
except Exception as e:
    # 错误回滚
    db.rollback()
finally:
    db.close()

 

 图片2.png

更新操作:

 

import pymysql

# 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语句传递参数
    # 提交
    db.commit()
except Exception as e:
    # 错误回滚
    db.rollback()
finally:
    db.close()

 

 



 图片3.png

 

删除操作:

 

 

import pymysql
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)) #传递参数
    #提交
    db.commit()
except Exception as e:
    #错误回滚
    db.rollback()
finally:
    db.close()

 

 图片4.png

 

数据库备份:

 图片5.png


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

图片6.png

 

 其实这里只是一个简单的备份,还可以加上time模块备份每一天有日期,另外还可以加上hash模块对密码进行加密,如果要想了解这两个模块的用发可以看看我的python分类中有相关的操作


猜你喜欢

转载自blog.51cto.com/xiaorenwutest/2154242