13

I have a part in my python script that I need to insert some data into a table on a mysql database example below:

insert_data = "INSERT into test (test_date,test1,test2) values (%s,%s,%s)"
cur.execute(insert_data,(test_date,test1,test2))
db.commit()
db.close()

I have a couple of questions what is incorrect with this syntax and how is possible to change the VALUES to timestamp instead of %s for string? Note the column names in the database are the same as the data stored in the variables in my script.

THanks

4 Answers 4

31

try this:

import MySQLdb
import time
import datetime

ts = time.time()
timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
conn = MySQLdb.connect(host= "localhost",
              user="root",
              passwd="newpassword",
              db="db1")
x = conn.cursor()

try:
   x.execute("""INSERT into test (test_date,test1,test2) values(%s,%s,%s)""",(timestamp,test1,test2))
   conn.commit()
except:
   conn.rollback()

conn.close()
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks what about the date? I need it to be inserted in this format yyyy-mm-dd hh:mm:ss
@StevenWilson please accept the answer if it helped you.
15

Timestamp creating can be done in one line, no need to use time.time(), just:

from datetime import datetime

timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

1 Comment

You forgot to import some stuff
0

Simply use the database NOW() function, e.g.

timestamp="NOW()"
insert_data = "INSERT into test (test_date,test1,test2) values (%s,%s,%s)"
cur.execute(insert_data,(test_date,test1,test2,timestamp))
db.commit()
db.close()

1 Comment

it doesn't work with %s placeholders, because it will throw the error "Incorrect datetime value", it's better to use datetime module as mentioned above.
0
insert_data = "INSERT into test (test_date,test1,test2) values (NOW(),%s,%s)"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.