Apricot Apricot - 4 years ago 169
MySQL Question

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?

Answer Source

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))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download