Python進行MySQL數(shù)據(jù)備份與增刪改查操作實戰(zhàn)指南
一、IDE工具介紹
生產(chǎn)環(huán)境還是推薦使用mysql命令行,但為了方便我們測試,可以使用Navicat之類的IDE工具。
二、MySQL 數(shù)據(jù)備份
1. 備份類型
物理備份
直接復(fù)制數(shù)據(jù)庫文件,這種方式適用于大型數(shù)據(jù)庫環(huán)境。不過,它存在一定局限性,不能恢復(fù)到異構(gòu)系統(tǒng)中,例如不能從 Linux 環(huán)境恢復(fù)到 Windows 環(huán)境。
邏輯備份
備份的是建表、建庫、插入等操作所執(zhí)行的 SQL 語句,比較適合中小型數(shù)據(jù)庫。但相對物理備份,其效率較低。
導出表
將表導入到文本文件中,方便數(shù)據(jù)的存儲和轉(zhuǎn)移。
2. 使用 mysqldump 實現(xiàn)邏輯備份
語法
# mysqldump -h 服務(wù)器 -u用戶名 -p密碼 數(shù)據(jù)庫名 > 備份文件.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
3. 恢復(fù)邏輯備份
方法一
[root@egon backup]# mysql -uroot -p123 < /backup/all.sql
方法二
mysql> use db1; mysql> SET SQL_LOG_BIN=0; mysql> source /root/db1.sql
如果備份/恢復(fù)單個庫時,可以修改 sql 文件,示例如下:
DROP database if exists school; create database school; use school;
4. 備份/恢復(fù)案例
數(shù)據(jù)庫備份/恢復(fù)實驗一:數(shù)據(jù)庫損壞
備份步驟
1. # mysqldump -uroot -p123 --all-databases > /backup/`date +%F`_all.sql
2. # mysql -uroot -p123 -e 'flush logs' //截斷并產(chǎn)生新的 binlog
3. 插入數(shù)據(jù) //模擬服務(wù)器正常運行
4. mysql> set sql_log_bin=0; //模擬服務(wù)器損壞
mysql> drop database db;
恢復(fù)步驟
1. # mysqlbinlog 最后一個 binlog > /backup/last_bin.log
2. mysql> set sql_log_bin=0;
mysql> source /backup/2014-02-13_all.sql //恢復(fù)最近一次完全備份
mysql> source /backup/last_bin.log //恢復(fù)最后個 binlog 文件
數(shù)據(jù)庫備份/恢復(fù)實驗二:如果有誤刪除
備份步驟
1. mysqldump -uroot -p123 --all-databases > /backup/`date +%F`_all.sql
2. mysql -uroot -p123 -e 'flush logs' //截斷并產(chǎn)生新的 binlog
3. 插入數(shù)據(jù) //模擬服務(wù)器正常運行
4. drop table db1.t1 //模擬誤刪除
5. 插入數(shù)據(jù) //模擬服務(wù)器正常運行
恢復(fù)步驟
1. # mysqlbinlog 最后一個 binlog --stop-position=260 > /tmp/1.sql
# mysqlbinlog 最后一個 binlog --start-position=900 > /tmp/2.sql
2. mysql> set sql_log_bin=0;
mysql> source /backup/2014-02-13_all.sql //恢復(fù)最近一次完全備份
mysql> source /tmp/1.log //恢復(fù)最后個 binlog 文件
mysql> source /tmp/2.log //恢復(fù)最后個 binlog 文件
注意事項
- 完全恢復(fù)到一個干凈的環(huán)境(例如新的數(shù)據(jù)庫或刪除原有的數(shù)據(jù)庫)。
- 恢復(fù)期間所有 SQL 語句不應(yīng)該記錄到 binlog 中。
5. 實現(xiàn)自動化備份
備份計劃
- 時間:2:00
- 備份數(shù)據(jù)庫:可根據(jù)需求指定
- 備份文件位置:可自定義
備份腳本
[root@xiao ~]# 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${user} -p${pass} --events --all-databases > ${back_dir}/${back_file} mysql -u${user} -p${pass} -e 'flush logs' # 只保留最近一周的備份 cd $back_dir find . -mtime +7 -exec rm -rf {} \;
手動測試
[root@xiao ~]# chmod a+x /mysql_back.sql [root@xiao ~]# chattr +i /mysql_back.sql [root@xiao ~]# /mysql_back.sql
配置 cron
[root@xiao ~]# crontab -l 2 * * * /mysql_back.sql
6. 表的導出和導入
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.html
LOAD 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 * from db1.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 為了安全考慮,對文件導出位置作了限制。需要在配置文件中設(shè)置:
[mysqld]
secure_file_priv='C:\\' #只能將數(shù)據(jù)導出到 C:\\ 下
重啟 MySQL 后重新執(zhí)行導出語句。
7. 數(shù)據(jù)庫遷移
務(wù)必保證在相同版本之間遷移,示例命令如下:
# mysqldump -h 源 IP -uroot -p123 --databases db1 | mysql -h 目標 IP -uroot -p456
三、pymysql 模塊
1. 安裝
pip3 install pymysql
2. 鏈接、執(zhí)行 sql、關(guān)閉(游標)
import pymysql user=input('用戶名: ').strip() pwd=input('密碼: ').strip() # 鏈接 conn=pymysql.connect(host='localhost',user='root',password='123',database='xiao',charset='utf8') # 游標 cursor=conn.cursor() # 執(zhí)行完畢返回的結(jié)果集默認以元組顯示 # cursor=conn.cursor(cursor=pymysql.cursors.DictCursor) # 執(zhí)行 sql 語句 sql='select * from userinfo where name="%s" and password="%s"' %(user,pwd) # 注意 %s 需要加引號 print(sql) res=cursor.execute(sql) # 執(zhí)行 sql 語句,返回 sql 查詢成功的記錄數(shù)目 print(res) cursor.close() conn.close() if res: print('登錄成功') else: print('登錄失敗')
3. execute() 之 sql 注入
最后那一個空格,在一條sql語句中如果遇到select * from t1 where id > 3 -- and name='xiao';則--之后的條件被注釋掉了
#1、sql注入之:用戶存在,繞過密碼 xiao' -- 任意字符 #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 的規(guī)矩來。
4. 增、刪、改:conn.commit()
import pymysql # 鏈接 conn=pymysql.connect(host='localhost',user='root',password='123',database='xiao') # 游標 cursor=conn.cursor() # 執(zhí)行 sql 語句 # part1 # sql='insert into userinfo(name,password) values("root","123456");' # res=cursor.execute(sql) # 執(zhí)行 sql 語句,返回 sql 影響成功的行數(shù) # print(res) # part2 # sql='insert into userinfo(name,password) values(%s,%s);' # res=cursor.execute(sql,("root","123456")) # 執(zhí)行 sql 語句,返回 sql 影響成功的行數(shù) # print(res) # part3 sql='insert into userinfo(name,password) values(%s,%s);' res=cursor.executemany(sql,[("root","123456"),("lhf","12356"),("eee","156")]) # 執(zhí)行 sql 語句,返回 sql 影響成功的行數(shù) print(res) conn.commit() # 提交后才發(fā)現(xiàn)表中插入記錄成功 cursor.close() conn.close()
5. 查:fetchone,fetchmany,fetchall
import pymysql # 鏈接 conn=pymysql.connect(host='localhost',user='root',password='123',database='xiao') # 游標 cursor=conn.cursor() # 執(zhí)行 sql 語句 sql='select * from userinfo;' rows=cursor.execute(sql) # 執(zhí)行 sql 語句,返回 sql 影響成功的行數(shù) rows,將結(jié)果放入一個集合,等待被查詢 # 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() # 提交后才發(fā)現(xiàn)表中插入記錄成功 cursor.close() conn.close()
6. 獲取插入的最后一條數(shù)據(jù)的自增 ID
import pymysql conn=pymysql.connect(host='localhost',user='root',password='123',database='xiao') 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()
到此這篇關(guān)于Python進行MySQL數(shù)據(jù)備份與增刪改查操作實戰(zhàn)指南的文章就介紹到這了,更多相關(guān)Python MySQL操作內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python+PyQt5實現(xiàn)MySQL數(shù)據(jù)庫備份神器
- python定時按日期備份MySQL數(shù)據(jù)并壓縮
- Python實現(xiàn)定時備份mysql數(shù)據(jù)庫并把備份數(shù)據(jù)庫郵件發(fā)送
- Python實現(xiàn)備份MySQL數(shù)據(jù)庫的方法示例
- python備份文件以及mysql數(shù)據(jù)庫的腳本代碼
- Python使用PyMySql增刪改查Mysql數(shù)據(jù)庫的實現(xiàn)
- pymysql實現(xiàn)增刪改查的操作指南(python)
- python對 MySQL 數(shù)據(jù)庫進行增刪改查的腳本
相關(guān)文章
pytest配置文件pytest.ini的配置、原理與實際應(yīng)用詳解
在Python的測試生態(tài)中,pytest無疑是最受歡迎的測試框架之一,在pytest的眾多配置文件中,pytest.ini無疑是最為重要和常用的一個,本文將深入探討pytest.ini的配置、工作原理以及實際應(yīng)用場景,幫助讀者更好地理解和使用這一強大的工具,需要的朋友可以參考下2025-03-03Python如何向現(xiàn)有的DataFrame添加新列示例代碼
Pandas庫中的DataFrame是處理表格數(shù)據(jù)的主要數(shù)據(jù)結(jié)構(gòu),添加新列有多種方法,包括使用現(xiàn)有列的值、創(chuàng)建全為零或全為一的列、或者直接添加一個由特定值組成的列,這些方法在處理數(shù)據(jù)時非常有用,需要的朋友可以參考下2024-11-11【Python】Python的urllib模塊、urllib2模塊批量進行網(wǎng)頁下載文件
這篇文章主要介紹了Python的urllib模塊、urllib2模塊批量進行網(wǎng)頁下載文件,就是一個簡單的從網(wǎng)頁抓取數(shù)據(jù)、下載文件的小程序,需要的可以了解一下。2016-11-11使用python查找windows系統(tǒng)中所有程序的安裝信息
這篇文章主要為大家介紹了使用python查找windows系統(tǒng)中所有程序的安裝信息示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-07-07Python使用plotly繪制數(shù)據(jù)圖表的方法
本篇文章主要介紹了Python使用plotly繪制數(shù)據(jù)圖表的方法,實例分析了plotly繪制的技巧,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07Python使用文件操作實現(xiàn)一個XX信息管理系統(tǒng)的示例
這篇文章主要介紹了Python使用文件操作實現(xiàn)一個XX信息管理系統(tǒng)的示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-07-07Python開發(fā)之QT解決無邊框界面拖動卡屏問題(附帶源碼)
朋友在學習QT的過程中,都會遇到各種問題,今天就QT無邊框拖動花屏問題給大家詳細介紹,究竟該如何解決呢,下面通過實例代碼和圖文相結(jié)合給大家詳細介紹,需要的朋友參考下吧2021-05-05