【问题标题】:Inserting datetime into a MS SQL table using pyodbc使用 pyodbc 将日期时间插入 MS SQL 表
【发布时间】:2014-08-18 22:27:20
【问题描述】:

我正在尝试使用 pyodbc 将日期时间值插入到 MS SQL Server 表中。 如果我手动执行,例如:

cursor.execute("""insert into currentvalue(value1,currentdatetime)
                                    values(55,'2014-06-27 16:42:48.533')""")

我完全没有问题,但是当我尝试这样做时:

currenttime = str(datetime.datetime.now())
cursor.execute("""insert into currentvalue(value1,currentdatetime) 
                                    values(55,"""+ currenttime+")")

我收到了这个错误:

SQL server '07' 附近的语法不正确,我认为是日期和开始时间之后的数字。

我也试过这个:

currenttime = "'"+str(datetime.datetime.now())+"'"

现在出现了这个错误:

从字符串转换日期和/或时间时转换失败。

【问题讨论】:

标签: python sql-server pyodbc mssql-jdbc


【解决方案1】:

去掉日期时间到字符串的转换,改为使用参数:

....
cursor.execute("insert into currentvalue (value1,currentdatetime) values(?,?)",
               (value1, datetime.datetime.now()))
....

【讨论】:

    【解决方案2】:

    您还可以使用 datetime.strftime() 以您需要的方式将 datetime 对象转换为字符串。 str(datetime) 是个坏主意。

    currenttime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f") cursor.execute("""insert into currentvalue(value1,currentdatetime) values(55,"""+ currenttime+")")

    【讨论】:

    • 我认为您的解决方案不起作用,就像提问者的第一次尝试一样。你至少需要一个字符串转义。
    猜你喜欢
    • 2014-08-20
    • 2016-07-16
    • 2013-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多