问题:如何在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
你的代码对我来说看起来很合理。问题如何表现出来?错误信息?插入了意外的日期值? ...? –