简体   繁体   English

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

[英]Can't insert Date and Time to sql server via pyodbc

I'm trying to insert date and time to SQL server in Linux (raspbian) environment using python language.So far i was able connect to MS Sql and also i created a table and im using pyodbc. 我正在尝试使用python语言在Linux(树莓派)环境中向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()

This part complied without any error.That means i have successfully created a table right? 这部分的编译没有任何错误。这意味着我已经成功创建了一个表,对吗? Or is there any issue? 还是有什么问题?

I try to add date and time this way. 我尝试以这种方式添加日期和时间。

   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()

But i get this error. 但是我得到这个错误。 pyodbc.ProgrammingError: pyodbc.ProgrammingError:

('HY004', '[HY004] [FreeTDS] [SQL Server]Invalid data type (O) (SQLBindParameter)') (“ HY004”,“ [HY004] [FreeTDS] [SQL Server]无效的数据类型(O)(SQLBindParameter)”)

help me please. 请帮帮我。 thanks in advance 提前致谢

If you are on Windows, install the latest version of the Microsoft ODBC Driver for SQL Server to ensure the DATE and TIME types are supported. 如果您使用的是Windows,请安装最新版本的SQL Server Microsoft ODBC驱动程序,以确保支持DATETIME类型。

If you are on Linux or macOS, use this page to determine the latest driver available for your distribution. 如果您使用的是Linux或macOS,请使用此页面确定可用于您的发行版的最新驱动程序。

Use parameter placeholders and pass the values as date and time objects for the current datetime value. 使用参数占位符,并将值作为当前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()

Note that the above code was only tested on Windows. 请注意,以上代码仅在Windows上进行了测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM