簡體   English   中英

如何在Python腳本中導入MySQL數據庫?

[英]How do I import a MySQL database in a Python script?

我在StackOverflow上已經看到過類似的問題,但是沒有找到有效的答案。 參見http://stackoverflow.com/questions/4408714/execute-sql-file-with-python-mysqldbhttp://stackoverflow.com/questions/10593876/execute-sql-file-in-python-with-mysqldb ?LQ = 1

這是我的代碼:

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)

您可以通過使用官方的MySQL Connector / Python及其cursor.execute方法中Multi參數來一次執行文件中的所有SQL。

引用第二個鏈接:

如果將multi設置為True ,則execute()能夠執行操作字符串中指定的多個語句。 它返回一個迭代器,該迭代器可以處理每個語句的結果。

鏈接中的示例代碼,稍作修改:

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM