pymysql模块对数据库的操作与备份-成都创新互联网站建设

关于创新互联

多方位宣传企业产品与服务 突出企业形象

公司简介 公司的服务 荣誉资质 新闻动态 联系我们

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

今天呢主要对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()#关闭连接

 

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

插入数据:

 

 

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模块对数据库的操作与备份

更新操作:

 

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()

 

 



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

 

删除操作:

 

 

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()

 

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

 

数据库备份:

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

#!/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模块对数据库的操作与备份

 

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


分享标题:pymysql模块对数据库的操作与备份
转载源于:http://kswsj.cn/article/gphhpg.html

其他资讯