2017-02-07 42 views
1

問題:如何在MS SQL服務器中插入日期時間值,給定以下代碼?將預定日期時間值插入到SQL表中

語境:

我有一個2-d名單在Python(即列表的列表),我想上傳到表中的Microsoft SQL Server 2008。對於這個項目我我正在使用Python的pymssql包。每個列表中的每個值都是一個字符串,除了第一個元素(它是日期時間值)之外。 這裏是我的代碼是如何讀取:

import pymssql 

db_connect = pymssql.connect(# these are just generic names 
    server = server_name, 
    user = db_usr, 
    password = db_pwd, 
    database = db_name 
    ) 

my_cursor = db_connect.cursor() 
for individual_list in list_of_lists: 
    # the first value in the paranthesis should be datetime 
    my_cursor.execute("INSERT INTO [DB_Table_Name] VALUES (%s, %s, %s, %s, %s, %s, %s, %s)", tuple(individual_list)) 
    db_connect.commit() 

Python解釋器有插入我的datetime值一個艱難的時間。據我所知,目前我有%s,它是一個字符串格式化程序,但我不確定我應該用什麼datetime,這是數據庫的第一列被格式化爲。

的「名單表」看起來像這樣(每個列表被轉換成一個元組後):

[(datetime.datetime(2012, 4, 1), '1', '4.1', 'hip', 'A1', 'J. Smith', 'B123', 'XYZ'),...] 

這裏的表應該是什麼樣子的說明:

+-----------+------+------+--------+-------+-----------+---------+---------+ 
| date | step | data | type | ID | contact | notif. | program | 
+-----------+------+------+--------+-------+-----------+---------+---------+ 
|2012-04-01 | 1 | 4.1 | hip | A1 | J. Smith | B123 | XYZ | 
|2012-09-05 | 2 | 5.1 | hip | A9 | B. Armst | B123 | ABC | 
|2012-01-16 | 5 | 9.0 | horray | C6 | F. Bayes | P995 | XYZ | 
+-----------+------+------+--------+-------+-----------+---------+---------+ 

先謝謝你。

+0

您可以顯示錶格中的列和來自列表的示例數據嗎? –

+0

@vkp看到我上面的編輯 - 謝謝! – daOnlyBG

+0

你的代碼對我來說看起來很合理。問題如何表現出來?錯誤信息?插入了意外的日期值? ...? –

回答

0

我會嘗試在插入前格式化日期時間爲「yyyymmdd hh:mm:ss」。隨着你在做什麼SQL將解析字符串,所以我也會建立整個字符串,然後插入字符串作爲變量。見下面

for individual_list in list_of_lists: 
    # the first value in the parentheses should be datetime 
    date_time = individual_list[0].strftime("%Y%m%d %H:%M:%S") 
    insert_str = "INSERT INTO [DB_Table_Name] VALUES (" + str(date_time) + "),(" + str(individual_list[1]) + ");" 
    print insert_str 
    my_cursor.execute(insert_str) 
    db_connect.commit() 

我爲粗蟒蛇道歉,但SQL應該喜歡這樣的INSERT語句,只要所有字段匹配。如果沒有,你可能想要指定這些值在你的插入語句中的哪些字段。

讓我知道這是否有效。

+0

這是一個網絡抓取項目的一部分;我已經有了字符串格式的日期。問題是我正在使用的數據庫的日期列格式爲'datetime'。如果無法上傳日期時間類型值,我只需要創建一個新的數據庫列作爲「varchar」並上傳我擁有的字符串。我想知道是否有辦法將值作爲日期時間值上傳,但不是字符串。 – daOnlyBG

+1

這是正確的。我不知道如何將一個Python日期時間對象添加到SQL字段。它需要採用SQL可以在插入字符串中識別的日期時間格式。 –

+1

(cc:@daOnlyBG)執行此操作的方法是使用*參數化查詢*:'crsr.execute(「UPDATE table1 SET dtmcol =%s WHERE ID =%s」,(datetime.datetime(2012,11,10 ),3))' –

相關問題