Ошибка: "_mysql_connector.MySQLInterfaceError: Commands out of sync; you can't run this command now" Python3.12, mysql.connector
Всех приветствую! Пытаюсь разобраться с MySQL в python и возникает такая проблема:
Ошибка:
Traceback (most recent call last):
File "/home/unvi/Рабочий стол/UNVI/UNVI-tools/Uapi/test.py", line 12, in <module>
core.database.setup.Setup()
File "/home/unvi/Рабочий стол/UNVI/UNVI-tools/Uapi/core/database/setup/__init__.py", line 24, in __init__
self.connect(database_setup)
File "/home/unvi/Рабочий стол/UNVI/UNVI-tools/Uapi/core/database/setup/__init__.py", line 38, in connect
obj(connection)
File "/home/unvi/Рабочий стол/UNVI/UNVI-tools/Uapi/core/database/setup/__init__.py", line 55, in general
connection.commit()
File "/home/unvi/Рабочий стол/UNVI/UNVI-tools/Uapi/venv/lib/python3.12/site-packages/mysql/connector/connection_cext.py", line 577, in commit
self._cmysql.commit()
_mysql_connector.MySQLInterfaceError: Commands out of sync; you can't run this command now
Еще логи:
2024-11-05 21:04:15,043 | WARNING - core.database.setup | Запущено
2024-11-05 21:04:15,043 | INFO - core.database.setup | Setup <bound method Setup.general of <core.database.setup.Setup object at 0x7fc4196b06b0>>
2024-11-05 21:04:15,054 | INFO - core.database.setup | Чтение general.sql
2024-11-05 21:04:15,054 | INFO - core.database.setup | Выполнение general.sql
Код:
class Setup:
def __init__(self):
logging.warning("core.database.setup | Запущено")
self.all_list = [self.general, self.game, self.data, self.catalog]
for database_setup in self.all_list:
self.connect(database_setup)
logging.info("core.database.setup | Завершено")
def connect(self, obj) -> None:
print(obj)
logging.info(f"core.database.setup | Setup {obj}")
try:
with connect(
host=MysqlUser.host,
user=MysqlUser.user,
password=MysqlUser.password,
) as connection:
obj(connection)
logging.info(f"core.database.setup | База данных успешно настроена! | {str(obj)}")
connection.close()
except Error as e:
logging.critical(
f"core.database.setup | Ошибка настройки базы данных\nError: {str(e)}",
exc_info=True
)
def general(self, connection) -> None:
logging.info("core.database.setup | Чтение general.sql")
with open("core/database/setup/general.sql") as setupfile:
setup_data = setupfile.read()
with connection.cursor() as cursor:
print("general: начало")
logging.info("core.database.setup | Выполнение general.sql")
cursor.execute(setup_data)
connection.commit()
cursor.close()
print("general: успешно")
def game(self, connection) -> None:
logging.info("core.database.setup | Чтение game.sql")
with open("core/database/setup/game.sql") as setupfile:
setup_data = setupfile.read()
with connection.cursor() as cursor:
logging.info("core.database.setup | Выполнение game.sql")
cursor.execute(setup_data)
connection.commit()
cursor.close()
print("game: успешно")
def data(self, connection) -> None:
logging.info("core.database.setup | Чтение data.sql")
with open("core/database/setup/data.sql") as setupfile:
setup_data = setupfile.read()
with connection.cursor() as cursor:
logging.info("core.database.setup | Выполнение data.sql")
cursor.execute(setup_data)
connection.commit()
cursor.close()
print("data: успешно")
def catalog(self, connection) -> None:
logging.info("core.database.setup | Чтение catalog.sql")
with open("core/database/setup/catalog.sql") as setupfile:
setup_data = setupfile.read()
with connection.cursor() as cursor:
logging.info("core.database.setup | Выполнение catalog.sql")
cursor.execute(setup_data)
connection.commit()
cursor.close()
print("catalog: успешно")
все sql файлы состоят таким образом:
CREATE DATABASE database_name;
USE database_name;
CREATE TABLE table_name(
ID INT PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
Буду очень благодарен за помощь)
Ответы (1 шт):
Автор решения: AnMaster
→ Ссылка
Конечно же, когда я задал вопрос - подумал, залез в документацию и нашел ответ. Для таких же как я отвечу:
я выполняю запрос не требующий комита, поэтому в данном случае connection.commit()
не нужен и код будет выглядеть примерно так:
def general(self, connection) -> None:
with open("core/database/setup/general.sql") as setupfile:
setup_data = setupfile.read()
with connection.cursor() as cursor:
cursor.execute(setup_data)
, конечно же, при условии что вы не записываете значения.