import pymysql
from pymysql.converters import escape_string
import os
import re
def connDB(dbname):
conn = pymysql.connect(host='127.0.0.1',port=3309,user='root',passwd='123456',charset='utf8',db=dbname)
cur=conn.cursor()
return (conn,cur)
#判断mysql数据库是否有mytest数据库,没有则创建
create_db_sql = "CREATE DATABASE IF NOT EXISTS `mytest` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
cur.execute(create_db_sql)
conn.commit()
#连接数据库mytest
conn,cur=connDB('mytest')
#读取sql文件
f=open('E:\\230629.sql','r',encoding="utf-8")
ss=f.read()
#正则取出sql语句并执行
ss=re.sub(r'-- .*\n','',ss)
ss=re.sub(r'\/\*[\s\S]*?(?<!")\*\/(?!")','',ss)
ss=re.sub(r'\n\n','\n',ss)
ss=ss.split(';\n')
for i in ss:
sql=re.sub(r'^\n','',i)
if sql!='':
cur.execute(sql)
conn.commit()
print(ss)
mysql的sql文件导入使用python导入到mysql数据库
于 2024-03-06 14:36:36 首次发布