Search code examples
pythonmysqlmysql-pythonmysql-connector

Python insert into MySQL - variable issue


I am trying to insert into several MySQL tables, the table name being a variable so I can insert ine the correct table. I dont understand what's wrong...

I created the function and use it:

METHOD 1 : I insert an information directly into the query >> it works

    import mysql.connector
    db = mysql.connector.connect(host="localhost", user="root", passwd="", database="test_base")
    mycursor = db.cursor()
    
    def testb(tablename):
        mycursor.execute(f"INSERT INTO `{tablename}` (Time, trade_ID, Price, Quantity) VALUES (%s,%s,%s,%s)",
                         ('69922825334', '239938314','19.97000000','25.03000000'))
        db.commit()
    
    
    testb('test_table')

METHOD 2 : I insert a information as a variable into the function I created >> it does not work


    def testb(tablename,Time, trade_ID, Price, Quantity):
        try:
            mycursor.execute(f"INSERT INTO `{tablename}` (Time, trade_ID, Price, Quantity) VALUES (%s,%s,%s,%s)",
                         ({Time}, {trade_ID}, {Price}, {Quantity}))
            db.commit()
        except Exception as e:
            print(e)
    
    testb('test_table','1678462365478','240219532','17.25000000','4.00000000')

error = Failed processing format-parameters; Python 'set' cannot be converted to a MySQL type


Solution

  • Use curly-braces only inside an f-string for your table name.

    Outside the f-string, curly-braces have a different meaning in Python expressions. It means to create a set.

    You don't need or want to put your variables into Python set structures. Just pass them as a list of variables:

    mycursor.execute(f"INSERT INTO `{tablename}` (Time, trade_ID, Price, Quantity) VALUES (%s,%s,%s,%s)",
      (Time, trade_ID, Price, Quantity))