python数据库操作批量sql执行_使用Python批量修改数据库执行Sql文件
由于上篇文章中批量修改了文件,有的時候數據庫也需要批量修改一下,之前的做法是使用寶塔的phpMyAdmin導出一個已經修改好了的sql文件,然后依次去其他數據庫里導入,效率不說極低,也算低了,且都是些重復性的勞動,所以打算用Python來批量執行sql
環境
版本:Python3.6
系統:MacOS
IDE:PyCharm
第三方庫:pymysql
Show Code
import?pymysql
host?=?'xxx.65.9.191'username?=?'root'password?=?'root'def?connectMySQL():
print('開始連接數據庫')????#?打開數據庫連接
db?=?pymysql.connect(host,username,password,charset='utf8')????#?使用?cursor()?方法創建一個游標對象?cursor
cursor?=?db.cursor()????#?使用?execute()?顯示所有數據庫
cursor.execute("SHOW?DATABASES")
print('開始查詢所有數據庫')????#?獲取所有數據庫名稱
data?=?cursor.fetchall()????#?開始操作
for?dbb?in?data:
dbname?=?dbb[0]
print('選中'?+?dbname?+?'數據庫')????????#?選擇數據庫
cursor.execute("use?"?+?dbname)????????#?查看有哪些表
cursor.execute("show?tables")
table?=?cursor.fetchall()????????#?如果不是3個表的就不管
if?len(table)?!=?3:????????????continue
for?tb?in?table:
tbname?=?tb[0]
print('開始刪除'+tbname+'表')????????????#?刪除所有的表
cursor.execute("DROP?TABLE?"?+?tbname)
executeScriptsFromFile('1.sql',?cursor)
db.close()def?executeScriptsFromFile(filename,cursor):
fd?=?open(filename,?'r',encoding='utf-8')
sqlFile?=?fd.read()
fd.close()
sqlCommands?=?sqlFile.split(';')????for?command?in?sqlCommands:????????try:
cursor.execute(command)????????except?Exception?as?msg:
print(msg)
print('sql執行完成')if?__name__?==?"__main__":
connectMySQL()
解釋代碼
這是用于執行sql文件,這里第一句就有個坑,最好設置encoding='utf-8'否則可能會報錯UnicodeEncodeError: 'latin-1' codec can't encode characters in position 41-44: ordinal not in range(256),當讀取了sql文件后用;分割語句然后用for循環依次執行sql語句
def?executeScriptsFromFile(filename,cursor):
fd?=?open(filename,?'r',encoding='utf-8')
sqlFile?=?fd.read()
fd.close()
sqlCommands?=?sqlFile.split(';')????for?command?in?sqlCommands:????????try:
cursor.execute(command)????????except?Exception?as?msg:
print(msg)
print('sql執行完成')
cha
這一段比較容易理解了,首先是連接數據庫,注意還是最好設置一下charset='utf8',因為我要操作多個數據庫執行sql文件,所以先把數據庫名稱全部獲取出來,這里獲取出來的結果是元組類型,即使for循環后出來的也是一個元組,所以用[0]取出元組中的值,然后選中數據庫執行刪表操作(當然不是每個人都要按我這些操作哈,需要執行啥操作就自己改SQL語句),表刪完了,然后開始執行1.sql文件,執行完成后關閉數據庫
def?connectMySQL():
print('開始連接數據庫')????#?打開數據庫連接
db?=?pymysql.connect(host,username,password,charset='utf8')????#?使用?cursor()?方法創建一個游標對象?cursor
cursor?=?db.cursor()????#?使用?execute()?顯示所有數據庫
cursor.execute("SHOW?DATABASES")
print('開始查詢所有數據庫')????#?獲取所有數據庫名稱
data?=?cursor.fetchall()????#?開始操作
for?dbb?in?data:
dbname?=?dbb[0]
print('選中'?+?dbname?+?'數據庫')????????#?選擇數據庫
cursor.execute("use?"?+?dbname)????????#?查看有哪些表
cursor.execute("show?tables")
table?=?cursor.fetchall()????????#?如果不是3個表的就不管
if?len(table)?!=?3:????????????continue
for?tb?in?table:
tbname?=?tb[0]
print('開始刪除'+tbname+'表')????????????#?刪除所有的表
cursor.execute("DROP?TABLE?"?+?tbname)
executeScriptsFromFile('1.sql',?cursor)
db.close()
這2篇文章的代碼從思路、編寫、到測試,用了一下午吧!我對Python也不是很熟悉,所以中間也踩了些坑,但確實能看出來,Python作為膠水語言拿來做這些小工具真的舒服!
總結
以上是生活随笔為你收集整理的python数据库操作批量sql执行_使用Python批量修改数据库执行Sql文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: lisp 线型虚实变换_绘画|虚实?国风
- 下一篇: redis set 超时_Redis 更