python入门教程13-05 (python语法入门之数据备份、pymysql模块)

python入门教程13-05 (python语法入门之数据备份、pymysql模块),第1张

概述本文实例讲述了Python读写及备份数据库 *** 作,以及pymysql模块的认识与 *** 作方法。一IDE工具介绍生产环境还是推荐使用mysql命令行,但为了方便我们测试,可以使用IDE工具掌握:#1.测试+链接数据库#2.新建库#3.新建表,新增字段+类型+约束#4.设计表:外键#5.新建查询#6.备份库/表#注意:批量

本文实例讲述了Python读写及备份数据库 *** 作,以及pyMysqL模块的认识与 *** 作方法。

一 IDE工具介绍

生产环境还是推荐使用MySQL命令行,但为了方便我们测试,可以使用IDE工具

掌握:

#1. 测试+链接数据库

#2. 新建库

#3. 新建表,新增字段+类型+约束

#4. 设计表:外键

#5. 新建查询

#6. 备份库/表

#注意:

批量加注释:ctrl+?键

批量去注释:ctrl+shift+?键

二 MysqL数据备份

#1. 物理备份: 直接复制数据库文件,适用于大型数据库环境。但不能恢复到异构系统中如windows。

#2. 逻辑备份: 备份的是建表、建库、插入等 *** 作所执行SQL语句,适用于中小型数据库,效率相对较低。

#3. 导出表: 将表导入到文本文件中。

一、使用MysqLdump实现逻辑备份

#语法

MysqLdump -h 服务器 -u用户名 -p密码 数据库名 > 备份文件.sql

#示例:

#单库备份

MysqLdump -uroot -p123 db1 > db1.sql

MysqLdump -uroot -p123 db1 table1 table2 > db1-table1-table2.sql

#多库备份

MysqLdump -uroot -p123 --databases db1 db2 MysqL db3 > db1_db2_MysqL_db3.sql

#备份所有库

MysqLdump -uroot -p123 --all-databases > all.sql

二、恢复逻辑备份

#方法一:

[root@egon backup]# MysqL -uroot -p123 < /backup/all.sql

#方法二:

MysqL> use db1;

MysqL> SET sql_LOG_BIN=0;

MysqL> source /root/db1.sql

#注:如果备份/恢复单个库时,可以修改sql文件

DROP database if exists school;

create database school;

use school;

三、备份/恢复案例

#数据库备份/恢复实验一:数据库损坏

备份:

MysqLdump -uroot -p123 --all-databases > /backup/date +%F_all.sqlMysqL -uroot -p123 -e ‘flush logs’ //截断并产生新的binlog

插入数据 //模拟服务器正常运行

MysqL> set sql_log_bin=0; //模拟服务器损坏

MysqL> drop database db;

恢复:

MysqLbinlog 最后一个binlog > /backup/last_bin.log

MysqL> set sql_log_bin=0;

MysqL> source /backup/2014-02-13_all.sql //恢复最近一次完全备份

MysqL> source /backup/last_bin.log //恢复最后个binlog文件

#数据库备份/恢复实验二:如果有误删除

备份:

MysqLdump -uroot -p123 --all-databases > /backup/date +%F_all.sql

MysqL -uroot -p123 -e ‘flush logs’ //截断并产生新的binlog

插入数据 //模拟服务器正常运行

drop table db1.t1 //模拟误删除

插入数据 //模拟服务器正常运行

恢复:

MysqLbinlog 最后一个binlog --stop-position=260 > /tmp/1.sqlMysqLbinlog 最后一个binlog --start-position=900 > /tmp/2.sqlMysqL> set sql_log_bin=0;

MysqL> source /backup/2014-02-13_all.sql //恢复最近一次完全备份

MysqL> source /tmp/1.log //恢复最后个binlog文件

MysqL> source /tmp/2.log //恢复最后个binlog文件

注意事项:

完全恢复到一个干净的环境(例如新的数据库或删除原有的数据库)

恢复期间所有SQL语句不应该记录到binlog中

四、实现自动化备份

备份计划:

什么时间 2:00

对哪些数据库备份

备份文件放的位置

备份脚本:

[root@egon ~]# vim /MysqL_back.sql

#!/bin/bash

back_dir=/backup

back_file=date +%F_all.sql

user=root

pass=123

if [ ! -d /backup ];then

mkdir -p /backup

fi

备份并截断日志

MysqLdump -u                                 u                         s                         e                         r                            −                    p                         {user} -p           user−p{pass} --events --all-databases >                                 b                         a                         c                                  k                          d                                 i                         r                            /                         {back_dir}/           backdir/{back_file}

MysqL -u                                 u                         s                         e                         r                            −                    p                         {user} -p           user−p{pass} -e ‘flush logs’

只保留最近一周的备份

cd $back_dir

find . -mtime +7 -exec rm -rf {} ;

手动测试:

[root@egon ~]# chmod a+x /MysqL_back.sql

[root@egon ~]# chattr +i /MysqL_back.sql

[root@egon ~]# /MysqL_back.sql

配置cron:

[root@egon ~]# crontab -l

2 * * * /MysqL_back.sql

五、表的导出和导入

SELECT… INTO OUTfile 导出文本文件

示例:

MysqL> SELECT * FROM school.student1

INTO OUTfile 'student1.txt’FIELDS TERMINATED BY ‘,’//定义字段分隔符

OPTIONALLY ENCLOSED BY ‘”’//定义字符串使用什么符号括起来

lines TERMINATED BY ‘\n’; //定义换行符

MysqL 命令导出文本文件

示例:# MysqL -u root -p123 -e ‘select * from student1.school’ > /tmp/student1.txt# MysqL -u root -p123 --xml -e ‘select * from student1.school’ > /tmp/student1.xml# MysqL -u root -p123 --HTML -e ‘select * from student1.school’ > /tmp/student1.HTMLLOAD DATA INfile 导入文本文件

MysqL> DELETE FROM student1;

MysqL> LOAD DATA INfile’/tmp/student1.txt’INTO table school.student1

FIELDS TERMINATED BY ','OPTIONALLY ENCLOSED BY '”'lines TERMINATED BY ‘\n’;

#可能会报错MysqL> select *fromdb1.emp into outfile’C:\db1.emp.txt’fIElds terminated by’,‘lines terminated by’\r\n’;

ERROR 1238 (HY000): Variable’secure_file_priv’is a read only variable#数据库最关键的是数据,一旦数据库权限泄露,那么通过上述语句就可以轻松将数据导出到文件中然后下载拿走,因而MysqL对此作了限制,只能将文件导出到指定目录在配置文件中

[MysqLd]

secure_file_priv=‘C:\’#只能将数据导出到C:\下重启MysqL

重新执行上述语句

六、数据库迁移

务必保证在相同版本之间迁移# MysqLdump -h 源IP -uroot -p123 --databases db1 | MysqL -h 目标IP -uroot -p456

三 pyMysqL模块

#安装pip3 install pyMysqL

一 链接、执行sql、关闭(游标)

import pyMysqL

user=input('用户名: ').strip()

pwd=input('密码: ').strip()

#链接

conn=pyMysqL.connect(host=‘localhost’,user=‘root’,password=‘123’,database=‘egon’,charset=‘utf8’)

#游标

cursor=conn.cursor() #执行完毕返回的结果集默认以元组显示

#cursor=conn.cursor(cursor=pyMysqL.cursors.DictCursor)

#执行SQL语句

sql=‘select * from userinfo where name="%s" and password="%s"’ %(user,pwd) #注意%s需要加引号

print(sql)

res=cursor.execute(sql) #执行SQL语句,返回SQL查询成功的记录数目

print(res)

cursor.close()

conn.close()

if res:

print('登录成功')

else:

print('登录失败')

二 execute()之sql注入

注意:符号–会注释掉它之后的sql,正确的语法:–后至少有一个任意字符

根本原理:就根据程序的字符串拼接name=’%s’,我们输入一个xxx’ – haha,用我们输入的xxx加’在程序中拼接成一个判断条件name=‘xxx’ – haha’

最后那一个空格,在一条SQL语句中如果遇到select *fromt1 where ID > 3 --andname=‘egon’;则–之后的条件被注释掉了#1、sql注入之:用户存在,绕过密码egon’ – 任意字符#2、sql注入之:用户不存在,绕过用户与密码xxx’ or 1=1 – 任意字符

解决方法:

原来是我们对sql进行字符串拼接# sql=“select * from userinfo where name=’%s’ and password=’%s’” %(user,pwd)# print(sql)# res=cursor.execute(sql)#改写为(execute帮我们做字符串拼接,我们无需且一定不能再为%s加引号了)sql=“select * from userinfo where name=%s and password=%s”#!!!注意%s需要去掉引号,因为pyMysqL会自动为我们加上res=cursor.execute(sql,[user,pwd])#pyMysqL模块自动帮我们解决sql注入的问题,只要我们按照pyMysqL的规矩来。

三 增、删、改:conn.commit()

import pyMysqL#链接conn=pyMysqL.connect(host=‘localhost’,user=‘root’,password=‘123’,database=‘egon’)#游标cursor=conn.cursor()#执行SQL语句#part1# sql=‘insert into userinfo(name,password) values(“root”,“123456”);’# res=cursor.execute(sql) #执行SQL语句,返回sql影响成功的行数# print(res)#part2# sql=‘insert into userinfo(name,password) values(%s,%s);’# res=cursor.execute(sql,(“root”,“123456”)) #执行SQL语句,返回sql影响成功的行数# print(res)#part3sql='insert into userinfo(name,password) values(%s,%s);'res=cursor.executemany(sql,[(“root”,“123456”),(“lhf”,“12356”),(“eee”,“156”)])#执行SQL语句,返回sql影响成功的行数print(res)

conn.commit() #提交后才发现表中插入记录成功cursor.close()

conn.close()

四 查:fetchone,fetchmany,fetchall

import pyMysqL#链接conn=pyMysqL.connect(host=‘localhost’,user=‘root’,password=‘123’,database=‘egon’)#游标cursor=conn.cursor()#执行SQL语句sql='select * from userinfo;'rows=cursor.execute(sql)#执行SQL语句,返回sql影响成功的行数rows,将结果放入一个集合,等待被查询# cursor.scroll(3,mode=‘absolute’) # 相对绝对位置移动# cursor.scroll(3,mode=‘relative’) # 相对当前位置移动res1=cursor.fetchone()

res2=cursor.fetchone()

res3=cursor.fetchone()

res4=cursor.fetchmany(2)

res5=cursor.fetchall()print(res1)print(res2)print(res3)print(res4)print(res5)print(’%s rows in set (0.00 sec)’%rows)

conn.commit() #提交后才发现表中插入记录成功cursor.close()

conn.close()’’’(1, ‘root’, ‘123456’)

(2, ‘root’, ‘123456’)

(3, ‘root’, ‘123456’)

((4, ‘root’, ‘123456’), (5, ‘root’, ‘123456’))

((6, ‘root’, ‘123456’), (7, ‘lhf’, ‘12356’), (8, ‘eee’, ‘156’))

rows in set (0.00 sec)’’’

五 获取插入的最后一条数据的自增ID

import pyMysqL

conn=pyMysqL.connect(host=‘localhost’,user=‘root’,password=‘123’,database=‘egon’)

cursor=conn.cursor()

sql='insert into userinfo(name,password) values(“xxx”,“123”);'rows=cursor.execute(sql)print(cursor.lastrowID)#在插入语句后查看conn.commit()

cursor.close()

conn.close()

总结

以上是内存溢出为你收集整理的python入门教程13-05 (python语法入门之数据备份、pymysql模块)全部内容,希望文章能够帮你解决python入门教程13-05 (python语法入门之数据备份、pymysql模块)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1187827.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存