无法通过pyodbc将日期和时间插入SQL Server

0 投票
1 回答
9136 浏览
提问于 2025-04-18 11:35

我正在尝试在Linux(raspbian)环境下,使用Python语言将日期和时间插入到SQL Server中。目前我已经成功连接到了MS SQL,并且创建了一个表,还在使用pyodbc这个库。

#! /user/bin/env python
import pyodbc 
import datetime

dsn = 'nicedcn'
user = myid
password = mypass
database = myDB

con_string = 'DSN=%s;UID=%s;PWD=%s;DATABASE=%s;' % (dsn, user, password, database)
cnxn = pyodbc.connect(con_string)
cursor = cnxn.cursor()

string = "CREATE TABLE Database3([row name] varchar(20), [my date] date), [my time]    time)"
cursor.execute(string)
cnxn.commit()

这一部分没有报错。这是不是意味着我成功创建了表?还是说还有什么问题呢?

我尝试用这种方式添加日期和时间。

   now = datetime.datetime.now()
    d1 = now.date()
    t2 = now.strftime("%H-%M-%S")
    cursor.execute("insert into Database3([row name], [my date], [my time]) values (?,?,?)", 
    ('new1', d1, t2))
    cnxn.commit()

但是我遇到了这个错误:pyodbc.ProgrammingError:

('HY004', '[HY004] [FreeTDS] [SQL Server]无效的数据类型 (O) (SQLBindParameter)')

请帮帮我。提前谢谢你!

1 个回答

3

如果你在使用Windows系统,记得安装最新版本的Microsoft ODBC驱动程序,这样才能确保DATETIME这两种数据类型可以正常使用。

如果你在使用Linux或macOS,可以访问这个页面,查看适合你系统的最新驱动程序。

在代码中使用参数占位符,并将当前的日期和时间作为日期时间对象传递。

now = datetime.datetime.now()
sql = "insert into Database3([row name], [my date], [my time]) values (?,?,?)"
cursor.execute(sql, ('new1', now.date(), now.time()))
cnxn.commit()

请注意,上面的代码只在Windows系统上进行了测试。

撰写回答