python数据库操作批量sql执行_利用Python如何批量修改数据库执行Sql文件

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值