問題:如何在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 |
+-----------+------+------+--------+-------+-----------+---------+---------+
先謝謝你。
您可以顯示錶格中的列和來自列表的示例數據嗎? –
@vkp看到我上面的編輯 - 謝謝! – daOnlyBG
你的代碼對我來說看起來很合理。問題如何表現出來?錯誤信息?插入了意外的日期值? ...? –