【发布时间】:2017-02-07 22:49:55
【问题描述】:
问题:如何将日期时间值插入 MS SQL 服务器,给出以下代码?
上下文:
我有一个 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 解释器很难插入我的日期时间值。我知道目前我有%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 在上面看到我的编辑-谢谢!
-
您的代码在我看来是合理的。问题是如何表现出来的?错误信息?插入了意外的日期值? ...?
标签: python sql sql-server datetime pymssql