学习 Python:
我有一组 .sql 文件并尝试使用 for 循环来执行它们的代码(每个文件都包含一个 drop-table 和一个 create-table 语句)
我正在使用一个具有各种方法来执行操作的类。
这是除了第一次迭代之外的每次迭代的错误(第一次迭代似乎工作正常)
2014 (HY000): Commands out of sync; you can't run this command now
我有点怀疑它与光标有关,但几个小时后我仍然不确定问题是什么......
这是我的代码
import re
import datetime
import mysql.connector
from mysql.connector import Error
from os import listdir
from os.path import isfile, join
class Migrator:
def __init__(self, host, user, password, database, port):
self.database = {
'host': host,
'user': user,
'password': password,
'database': database,
'port': port
}
self.db_connection = self.db_connect()
# here i store the cursor
self.db_cursor = self.db_connection.cursor()
def __del__(self):
self.db_connection.close()
files_tables = {
'X00': 'table1_x00',
'X01': 'table2_x01',
'X02': 'table3_x02',
'X03': 'table4_x03',
'X04': 'table5_x04',
}
# connect to db
def db_connect(self):
try:
connection = mysql.connector.connect(
host=self.database['host'],
user=self.database['user'],
password=self.database['password'],
database=self.database['database'],
port=self.database['port']
)
if connection.is_connected():
db_Info = connection.get_server_info()
print("Connected to MYSQL Server version ", db_Info)
cursor = connection.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
print("Successfully connected to database: ", record)
return connection
except Error as e:
print('Error while connecting to MySQL', e)
mydb = mysql.connector.connect(
host=self.database['host'],
user=self.database['user'],
password=self.database['password'],
database=self.database['database'],
port=self.database['port']
)
return mydb
def read_filelist(self, path):
'''This method reads out all files and returns their names in a list'''
onlyfiles = [f for f in listdir(path) if isfile(join(path, f))]
onlyfiles_sorted = sorted(onlyfiles)
return onlyfiles_sorted
def create_table_all(self, path):
'''This creates all the tables without they relationships to other tables'''
errors = 0
filelist = self.read_filelist(path)
for file in filelist:
f = open(path + "/" + file)
sql = f.read()
f.close()
try:
self.db_cursor.execute(sql)
except mysql.connector.Error as e:
print(e)
test_instance = Migrator('127.0.0.1', 'root', 'test', 'test_database', 3308)
# this is the folder which contains the files
test_instance.create_table_all('../../../../build/entity_tables_create_only')