skip to Main Content

I cannot see why my defined function does not work. No error message, just no INSERT into the Table

I define my function:

import mysql.connector
db = mysql.connector.connect(host="localhost", user="root", passwd="", database="autot")
mycursor = db.cursor()

def writedb(Tablename,Time, trade_ID, Price, Quantity):
    mycursor.execute("INSERT INTO '{Tablename}' (Time, trade_ID, Price, Quantity) VALUES (%s,%s,%s,%s)", 
                     ({Time},{trade_ID}, {Price}, {Quantity}))
    db.commit()

I then use my function:

writedb(msft_price, 1678440087934, 240165117, 16.73000000, 97)

nothing happens…

4

Answers


  1. Chosen as BEST ANSWER

    Thank you community. The problems lied around the single quotes around table name. I replaced them with back-ticks `


  2. The db.commit() should be inside the scope of writedb, add a TAB 😅

    Login or Signup to reply.
  3. Your statement uses {Tablename} but is not an f-string (meaning it doesn’t start with f"…{Tablename}…".

    Try using .format() instead of the current curly braces:

    def writedb(Tablename, Time, trade_ID, Price, Quantity):
        mycursor.execute("INSERT INTO '{0}' (Time, trade_ID, Price, Quantity) VALUES (%s,%s,%s,%s)".format(Tablename), 
                     (Time, trade_ID, Price, Quantity))
        db.commit()
    
    Login or Signup to reply.
  4. Try this code,

    import pymysql
    conn=pymysql.connect(host="localhost", user="root", passwd="", database="autot")
    cur  = conn.cursor()
    
    def insertData(Tablename,Time,trade_ID,Price,Quantity):
        try :
            cur.execute(f"INSERT INTO '{Tablename}' (Time, trade_ID, Price, Quantity) VALUES ({Time},{trade_ID}, {Price}, {Quantity})")
            conn.commit()
        except Exception as e:
            conn.rollback()
    
    
    insertData('msft_price', 1678440087934, 240165117, 16.73000000, 97)
    
    conn.close()
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search