Fail to insert data into mysql table using python script

Issue

i’m trying to insert data from my python script into my sql table. The script run with no error, however when i check in the table no data actually inserted. I have search around the internet and still couldn’t figure out what is the problem. Any help would be very appreciated. Code below is what i’ve tried so far.

 ts = time.time()
    timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
    try:
        mydb = mysql.connector.connect(host="localhost", user="root", passwd="", database="dummy_monke")
        mycursor = mydb.cursor()  # to point at database table
        queries = "INSERT INTO monitoring(id,lp,time) values (%s, %s, %s)"
        mycursor.execute(queries,spliced, timestamp)
        mydb.commit()
        print(mycursor.rowcount, "record updated successfully")

    except:
        mydb.rollback()
        print("record fail to update")

Solution

Based on this post, you can do

queries = "INSERT INTO monitoring(lp,time) values (%s, %s)"
mycursor.execute(queries, (spliced, timestamp))

to generate a tuple on the fly and have the auto-increment done for you.

Side note: it may make sense to rename queries to a singular query.

Answered By – t_krill

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published