我正在使用 pyodbc 查询包含 DATE 类型列的 SQL Server 2008 数据库表。
生成的数据行包含日期字符串而不是 python datetime.date 或 datetime.datetime 实例。
这似乎只是 DATE 类型列的问题; DATETIME 类型的列被正确处理并返回 datetime.datetime 实例。
例子
import pyodbc
from pprint import pformat
db = pyodbc.connect("DRIVER={SQL Server};SERVER=.\\SQLEXPRESS;DATABASE=scratch;Trusted_Connection=yes")
print pformat(db.cursor().execute("select * from Contract").description)
结果:
(('id', <type 'int'>, None, 10, 10, 0, False),
('name', <type 'str'>, None, 23, 23, 0, False),
('some_date', <type 'unicode'>, None, 10, 10, 0, True),
('write_time', <type 'datetime.datetime'>, None, 23, 23, 3, False))
请注意,some_date 列表示为 unicode 字符串类型,但是,在数据库中,此列定义为 DATE:
CREATE TABLE dbo.Contract(
id INT NOT NULL,
name VARCHAR(23) NOT NULL,
some_date DATE NULL,
write_time DATETIME NOT NULL)
这是否正常,我怎样才能最好地纠正它?
最佳答案
使用 SQL Server native 客户端。例如将 Driver={SQL Server Native Client 10.0} 放入您的连接字符串中,而不是 DRIVER={SQL Server}。
使用 SQL Server ODBC 驱动程序重现了您的场景,其中日期作为字符串返回。当使用 2008+ 兼容版本的 SQL Server native 客户端时,日期类型按预期返回,但 datetime2 似乎作为字符串返回(在我的有限测试中)。
表定义:
create table dbo.datetest (
[date] date not null,
[datetime] datetime not null,
[datetime2] datetime2 not null
);
insert into
dbo.datetest
values
(CAST(current_timestamp as DATE),
CAST(current_timestamp as datetime),
CAST(current_timestamp as datetime2));
例子:
import pyodbc
from pprint import pformat
db = pyodbc.connect(driver='{SQL Server Native Client 10.0}',
server='TESTSRVR', database='TESTDB',
trusted_connection='yes')
print pformat(db.cursor().execute("select * from dbo.datetest").description)
结果:
(('date', <type 'datetime.date'>, None, 10, 10, 0, False),
('datetime', <type 'datetime.datetime'>, None, 23, 23, 3, False),
('datetime2', <type 'unicode'>, None, 27, 27, 0, False))
关于python - pyodbc 将 SQL Server DATE 字段作为字符串返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7172540/