pymysql执行sql脚本

从网上搜索了半天也没有合适的,大多是以;分隔后直接执行, 但是这样会存在注释的问题。一般导出的sql文件中,都包含了大量的注释;

import pymysql

def mysql_init():
    # conf 包含mysql的一些配置
    con = pymysql.connect(host=conf.get('db', 'mysql_uri'),
                          port=conf.getint('db', 'mysql_port'),
                          user=conf.get('db', 'mysql_username'),
                          password=conf.get('db', 'mysql_password'),
                          charset='utf8')
    cur = con.cursor()
    cur.execute("create database test character set utf8;")
    con.close()
    sync_mysql_data('test', "test.sql")
    print '初始化mysql数据成功'


def sync_mysql_data(db, file):
    with open(file, "r") as f:  # 打开文件
        data = f.read()
        lines = data.splitlines()
        sql_data = ''
	# 将--注释开头的全部过滤,将空白行过滤
        for line in lines:
            if len(line) == 0:
                continue
            elif line.startswith("--"):
                continue
            else:
                sql_data += line
        sql_list = sql_data.split(';')[:-1]
        sql_list = [x.replace('\n', ' ') if '\n' in x else x for x in sql_list]
    con = pymysql.connect(host=conf.get('db', 'mysql_uri'),
                          port=conf.getint('db', 'mysql_port'),
                          user=conf.get('db', 'mysql_username'),
                          password=conf.get('db', 'mysql_password'),
                          database=db,
                          charset='utf8')
    cur = con.cursor()
    for sql_item in sql_list:
        print sql_item
        cur.execute(sql_item)
    con.close()
posted @ 2020-11-23 20:53  faylinn  阅读(2059)  评论(0编辑  收藏  举报
、、、