簡體   English   中英

使用pyodbc將日期時間插入MS SQL表

[英]Inserting datetime into a MS SQL table using pyodbc

我正在嘗試使用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服務器'07'附近的語法不正確,我認為這是日期和開始時間之后的數字。

我也試過這個:

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

現在出現這個錯誤:

從字符串轉換日期和/或時間時轉換失敗。

刪除日期時間到字符串轉換,而不是使用參數:

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

您還可以使用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+")")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM