【问题标题】:Can't insert Date and Time to sql server via pyodbc无法通过 pyodbc 将日期和时间插入 sql server
【发布时间】:2014-08-20 21:37:35
【问题描述】:

我正在尝试使用 python 语言在 Linux (raspbian) 环境中向 SQL 服务器插入日期和时间。到目前为止,我能够连接到 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)')

请帮帮我。提前致谢

【问题讨论】:

  • 我对 python 并不太熟悉,但你有没有试过用冒号代替破折号"%H:%M:%S"
  • 您使用的是什么版本的 SQL Server 本机客户端?
  • 我正在使用 MS SQL 2008 R2 Express
  • "%H:%M:%S" 是的,我试过了,但我得到了相同的结果
  • @Kevin777 2008 R2 Express 是您使用的 SQL Server 版本,而不是 ODBC 驱动程序的版本。您的 DSN 中使用了哪个版本的 SQL Server ODBC 驱动程序?这可以使用ODBC Data Source Administrator 找到。

标签: python sql date time pyodbc


【解决方案1】:

如果您使用的是 Windows,请安装最新版本的 Microsoft ODBC Driver for SQL Server 以确保支持 DATETIME 类型。

如果您使用的是 Linux 或 macOS,请使用此 page 确定可用于您的发行版的最新驱动程序。

使用参数占位符并将值作为datetime 对象传递给当前日期时间值。

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 上测试过。

【讨论】:

  • 我在 Linux (raspberry pi) 上
  • @Kevin777 更新了 Microsoft ODBC Driver for SQL Server on Linux 的文档链接
  • 如果我的数据类型有任何问题??
  • datetime 数据类型是在 SQL Server 2008 中引入的。将 FreeTDS 升级到最新版本,或在 Linux 上使用 Microsoft ODBC Driver for SQL Server。
猜你喜欢
  • 1970-01-01
  • 2014-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多