I’m trying to log data to table in MySQL. First function is to connect the database, second is to create table, third one is to actually log data. But after connect to database from first function, other functions can’t connect the cursor.
I tried to put create table in first function and it works fine, but I want separately. And tried max-packet size, also no effects.
def initialize_database():
MySQL = mysql.connector.connect(host=MySQL_HOST,database="records",user=MySQL_USERNAME,password=MySQL_PASSWORD)
if MySQL.is_connected():
db_Info = MySQL.get_server_info()
print("Connected to MySQL Server version ", db_Info)
cursor = MySQL.cursor()
cursor.execute("select database();")
response = cursor.fetchone()
return cursor
def database_create_table(device_id:str,device_type:str,device_name:str):
Query = ""
cursor = initialize_database()
if device_type == "light":
Query = "CREATE TABLE ",device_name," (",device_id," varchar(30) NOT NULL,power_state int NOT NULL,brightness_level int NOT NULL,PRIMARY KEY (",device_id,"))"
result = cursor.execute(Query)
print("Table created successfully")
Here’s what error code
Traceback (most recent call last):
File “PycharmProjects\tuya-connector-python\example\mainfunctions.py”, line 56, in
database_create_table(DEVICES_ID[0],”light”,”yeah”)
File “PycharmProjects\tuya-connector-python\example\mainfunctions.py”, line 36, in database_create_table
result = cursor.execute(mySql_Create_Table_Query)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “PycharmProjects\tuya-connector-python\venv\Lib\site-packages\mysql\connector\cursor_cext.py”, line 302, in execute
raise ProgrammingError(“Cursor is not connected”, 2055) from err
mysql.connector.errors.ProgrammingError: 2055: Cursor is not connected
Please edit your post and add exact error traceback. It doesn’t work (i.e., can’t connect) is not a helpful descriptor for us.
Aside – reconsider your database design in creating a separate table for each device name. For scalability, maintainability, and efficiency, generalize your schema for a single
device
table with a singledevice_id
column.always put FULL error message (starting at word “Traceback”) in question (not in comments) as text (not screenshot, not link to external portal). There are other useful information in the full error/traceback.
maybe you should
close
connection before you try to open it again. OR maybe you should runconnection
only once – at start, outside functions, and keep in global variable – and later run it only whenMySQL.is_connected()
givesFalse