python 利用pymysql 导入sql文件,生成数据库

pip install pymysql

import pymysql

host = "127.0.0.1"
user = "root"
password = ""
db = "ceshi_install"

conn = pymysql.connect(host=host, user=user, password=password, database=db)  # 连接数据库
cursor = conn.cursor()  # 创建游标
a = 0

try:
    with open('xc_ghavu_com.sql', 'r', encoding='utf-8') as f:
        sql = ''
        for i in f:
            if i == '\n' or i[0] == '/' or i[0] == '-':
                pass
            else:
                a = a + 1
                # 处理空行
                i = i.strip()
                i = i.strip('\r')
                i = i.strip('\n')
		# 构造字符串
                sql = sql + i
		# 判断此行sql语句中是否只含有 ‘;’ ,如果含有,则进行判断是否在结尾,反之,继续拼接
                if ';' in i:
                    pot = i.rfind(';')
                    if pot + 1 == len(i):
                        cursor.execute(sql)
                        sql = ''
    conn.commit()
    cursor.close()  # 关闭游标
    conn.close()  # 关闭连接
    print("创建成功")
except Exception as e:
    # 失败后的回滚操作
    conn.rollback()
    cursor.close()
    conn.close()
    print("创建失败: ", e)

print('----------', a)


posted @ 2022-04-17 14:36  李鑫森  阅读(499)  评论(0)    收藏  举报