今天呢主要对pyMySQL模块进行使用讲解一下:
创新互联是一家专业提供灵寿企业网站建设,专注与网站设计、成都网站设计、H5页面制作、小程序制作等业务。10年已为灵寿众多企业、政府机构等服务。创新互联专业网站设计公司优惠进行中。
https://www.cnblogs.com/lilidun/p/6041198.html
Linux系统上安装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)  # 执行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()#关闭连接
 
插入数据:
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()
 
更新操作:
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语句传递参数
    # 提交
    db.commit()
exceptExceptionase:
    # 错误回滚
    db.rollback()
finally:
    db.close()
 
删除操作:
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))#传递参数
    #提交
    db.commit()
exceptExceptionase:
    #错误回滚
    db.rollback()
finally:
    db.close()
 
数据库备份:
 
#!/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""")

其实这里只是一个简单的备份,还可以加上time模块备份每一天有日期,另外还可以加上hash模块对密码进行加密,如果要想了解这两个模块的用发可以看看我的python分类中有相关的操作
文章名称:pymysql模块对数据库的操作与备份
新闻来源:http://www.scyingshan.cn/article/gphhpg.html

 建站
建站
 咨询
咨询 售后
售后
 建站咨询
建站咨询 
 