简体   繁体   中英

Insert into mysql python - not working

I have created the following table in MySQL

create table DT (Date varchar(20), Time varchar(20))

I am using the following python code to insert into mysql. I am not getting any error nor the date and time is getting written into mysql.

import mysql.connector
from datetime import datetime

conn = mysql.connector.connect(host = 'localhost', database = 'mydatabase', user = 'root', password = '')
cursor = conn.cursor()
i = datetime.now()
xdate = i.strftime('%Y-%m-%d')
xtime = i.strftime('%H-%M-%S')
sqql = 'insert into DT (Date, Time) values (%s,%s);'
cursor.execute(sqql, xdate, xtime)
conn.commit()
conn.close()

I am not getting any error nor getting the date and time inserted into mysql. However when I directly do the insert in mysql it works..

insert into DT (Date, Time) values ('2017-02-06', '19-54-36');

Not sure how to resolve? Can someone help?

You are not passing the query parameters correctly, put them into a tuple, replace:

cursor.execute(sqql, xdate, xtime)

with:

cursor.execute(sqql, (xdate, xtime))

According to this example and the documentation , the method cursor.execute() takes a string query as first parameter, and the second parameter is a tuple or a dictionary that contains the values of that query. So you should call the method this way:

cursor.execute(sqql, (xdate, xtime))

In case you are using xdate and xtime just in this invocation, you can even simplify this call by:

cursor.execute(sqql, (i.strftime('%Y-%m-%d'), i.strftime('%H-%M-%S')))

In addition, you can also use a dictionary in order to improve the readability of the code:

sqql = 'insert into DT (Date, Time) values (%(xdate)s, %(xtime)s);'
cursor.execute(sqql, {'xdate': `xdate`, 'xtime`: xtime})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM