本文介绍了使用 pyodbc 将日期时间插入到 MS SQL 表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 pyodbc 将日期时间值插入到 MS SQL Server 表中.如果我手动执行,例如:
I'm trying to insert a datetime value into a MS SQL Server table using pyodbc.If I do it manually, something like:
cursor.execute("""insert into currentvalue(value1,currentdatetime)
values(55,'2014-06-27 16:42:48.533')""")
我完全没有问题,但是当我尝试这样做时:
I have no problem at all, but when I try to do:
currenttime = str(datetime.datetime.now())
cursor.execute("""insert into currentvalue(value1,currentdatetime)
values(55,"""+ currenttime+")")
我收到此错误:
SQL server '07' 附近的语法不正确,我认为这是日期和开始时间之后的数字.
我也试过这个:
currenttime = "'"+str(datetime.datetime.now())+"'"
现在出现这个错误:
从字符串转换日期和/或时间时转换失败.
推荐答案
去掉日期时间到字符串的转换,改为使用参数:
Remove the datetime to string conversion and instead use parameters:
....
cursor.execute("insert into currentvalue (value1,currentdatetime) values(?,?)",
(value1, datetime.datetime.now()))
....
这篇关于使用 pyodbc 将日期时间插入到 MS SQL 表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!