Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

python - 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.

#! /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:

('HY004', '[HY004] [FreeTDS] [SQL Server]Invalid data type (O) (SQLBindParameter)')

help me please. thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

If you are on Linux or macOS, use this page to determine the latest driver available for your distribution.

Use parameter placeholders and pass the values as date and time objects for the current datetime value.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...