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模块对数据库的操作与备份
标题网址:https://www.cdcxhl.com/article36/gphhpg.html

成都网站建设公司_创新互联,为您提供微信小程序品牌网站设计ChatGPT用户体验网站策划动态网站

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

手机网站建设