Updating Date & Time into MySQL via python

让人想犯罪 __ 提交于 2021-02-11 08:24:40

问题


I am trying to update my date & time columns in my MySQLdb database. I have 2 columns by the name date1 and time1 and both are type TEXT. This is my python code

import MySQLdb
import datetime

db = MySQLdb.connect('localhost','admin','admin','dbname')
cur = db.cursor()

a = datetime.datetime.strftime(datetime.date.today(),'%Y-%m-%d'))
cur.execute('update Data set date1={0}'.format(a))
db.commit()

But after this code executes I see the value in the column set as '2000'.

I tried several datetypes in MySQL - varchar2, date, datetime but they always show as '2000' or '0000-00-00'.

When I run this sql query directly it works fine:

UPDATE `Data` SET `date1`='22-04-1994'

I googled this error and tried this:

a = datetime.date.today()
a = a.isoformat()

But it shows in the database as 2000.

Edit: I tried using {0} instead of +a. Still coming as 2000.

I am using Mysql version 5.5.51-38.2


回答1:


Think what your query does, since you concatenate strings. You can even print it out. Since you don't put the date into quotes it will be considered a calculation. So you're saying:

date1=2016-11-5

This is of course 2000, but you want

date1='2016-11-5'

The best way is to use parameters so the underlying system is doing all this for you rather than you concatenating strings and trying to escape them correctly.




回答2:


You should be using parameters. But, if not, you need to include single quotes around date constants:

cur.update('update Data set date1 = '{0}'".format(a))


来源:https://stackoverflow.com/questions/40441722/updating-date-time-into-mysql-via-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!