![](/img/trans.png)
[英]Unable to match python datetime.date object with sqlite DATE
[英]python datetime.date not match SQL date
我有一些數據,我想插入到 netezza 的表中:
import pyodbc
data=[['GZ', datetime.date(2017, 2, 8), 19.7, 10.7, 0, '1級'],
['GZ', datetime.date(2017, 2, 9), 16.3, 9.7, -1, '微風'],
['GZ', datetime.date(2017, 2, 10), 16.0, 10.0, -1, '微風']]
conn = pyodbc.connect("DRIVER={NetezzaSQL}; SERVER=**;DATABASE=weather; UID=**; PASSWORD=**;")
cur = conn.cursor()
for i in data:
cur.execute("""
insert into WEATHER_INFO(location,weather_date,high_tempature,low_tempature,weather,wind)
values(\'%s\',%s,%s,%s,%s,\'%s\')
""" % (i[0], i[1], i[2], i[3], i[4], i[5]))
conn.commit()
cur.execute('select * from WEATHER_INFO')
print(cur.fetchall())
cur.close()
conn.close()
我得到一些錯誤:
pyodbc.Error: ('HY000', "[HY000] ERROR: Attribute 'WEATHER_DATE' is of type 'DATE'
but expression is of type 'INT4'\n\tYou will need to rewrite or cast the expression (46)
(SQLExecDirectW)")
這是表結構:
create table weather(
location varchar(20),
weather_date date,
high_tempature float(4,1),
low_temputare float(4,1),
weather int(11),
wind varchar(20)
);
我知道 python datime.date 應該匹配 SQL 日期。 我沒有通過搜索 stackoverflow 得到我想要的答案。 那么我應該如何解決這個問題?
您的問題是您正在使用字符串格式化運算符%
來創建動態 SQL,而這些 SQL 語句格式錯誤。 如果我們打印出您嘗試執行的實際語句,它們看起來像
insert into WEATHER_INFO(location,weather_date,high_tempature,low_tempature,weather,wind)
values('GZ',2017-02-08,19.7,10.7,0,'1級')
請注意,日期值插入為2017-02-08
,沒有分隔符,因此它被解釋為整數表達式。
您需要做的是使用適當的參數化查詢:
sql = """\
insert into WEATHER_INFO(location,weather_date,high_tempature,low_tempature,weather,wind)
values(?,?,?,?,?,?)
"""
for i in data:
cur.execute(sql, i)
conn.commit()
或者也許只是
sql = """\
insert into WEATHER_INFO(location,weather_date,high_tempature,low_tempature,weather,wind)
values(?,?,?,?,?,?)
"""
cur.executemany(sql, data)
conn.commit()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.