- Navicat转储的sql文件的截图:
- python3中利用pymsql读取文件并重新恢复数据(当数据库中数据被更改后)
import pymysql
def read_sql_file(file_path):
with open(file_path, 'r', encoding='utf8') as f:
sql_list = []
for line in f.readlines():
if line.startswith('SET'):
sql_list.append(line.replace('\n', ''))
elif line.startswith('DROP'):
sql_list.append(line.replace('DROP', 'TRUNCATE').replace(' IF EXISTS', '').replace('\n', ''))
elif line.startswith('INSERT'):
sql_list.append(line.replace('\n', ''))
else:
pass
return sql_list
if __name__ == '__main__':
path = "xxx.sql"
connect = pymysql.connect(
host='localhost',
user='xxx',
password='xxx',
database='xxx',
port=3306,
charset='utf8'
)
cursor = connect.cursor()
for sql in read_sql_file(path):
cursor.execute(sql)
connect.commit()
cursor.close()
connect.close()