如何在 Python 脚本中导入 MySQL 数据库?

How do I import a MySQL database in a Python script?

我在 Whosebug 上看到过一些类似的问题,但没有找到有效的答案;见 AND

这是我的代码:

import pymysql
import sys
import access  # holds credentials
import mysql_connector  # connects to MySQL, is fully functional


class CreateDB(object):
    def __init__(self):
        self.cursor = None
        self.conn = pymysql.connect(host, user, passwd)

    def create_database(self):
        try:
            with self.conn.cursor() as cursor:
                for line in open('file.sql'):
                    cursor.execute(line)
            self.conn.commit()

        except Warning as warn:
            f = open(access.Credentials().error_log, 'a')
            f.write('Warning: %s ' % warn + '\nStop.\n')
            sys.exit()

create = CreateDB()
create.create_database()

当我 运行 我的脚本出现以下错误时:

pymysql.err.InternalError: (1065, 'Query was empty')

当我直接通过 MySQL 导入时,我的 .sql 文件已成功加载,文件的每一行都有一个查询。有人对此有解决方案吗?我遵循了其他帖子的建议,但没有成功。

通过以下方式处理文件末尾的空行:

if line.strip(): cursor.execute(line)

您可以一次执行文件中的所有SQL,使用官方MySQL Connector/Python and the Multi parameter in its cursor.execute method

引自第二个 link:

If multi is set to True, execute() is able to execute multiple statements specified in the operation string. It returns an iterator that enables processing the result of each statement.

来自 link 的示例代码,稍作修改:

import mysql.connector

file = open('script.sql')
sql = file.read()


cnx = mysql.connector.connect(user='u', password='p', host='h', database='d')
cursor = cnx.cursor()

for result in cursor.execute(sql, multi=True):
  if result.with_rows:
    print("Rows produced by statement '{}':".format(
      result.statement))
    print(result.fetchall())
  else:
    print("Number of rows affected by statement '{}': {}".format(
      result.statement, result.rowcount))

cnx.close()