温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-07-29 15:00:44 来源:网络 阅读:1498 作者:tty之星 栏目:编程语言

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

 

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

插入数据:

 

 

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

 

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

更新操作:

 

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

 

 



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

 

删除操作:

 

 

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

 

 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分类中有相关的操作


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI