2017-02-07 41 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))' –

相关问题