Python执行sql脚本
import pymysql
try:
conn = pymysql.connect(host = '127.0.0.1',user = 'root',passwd = 'root',port = 3306,db = 'test',charset = 'utf8')
cur = conn.cursor()
with open('test.sql',encoding='utf-8',mode='r') as file:
sql_list = file.read().split(';')[:-1]
for sql in sql_list:
if '\n' in sql:
sql = sql.replace('\n', ' ')
if ' ' in sql:
sql = sql.replace(' ', '')
sql_item = sql+';'
cur.execute(sql_item)
print("执行成功sql : %s"%sql_item)
except Exception as e:
print(e)
print('执行失败sql : %s'%sql_item)
finally:
cur.close()
conn.commit()
conn.close()