gpt4 book ai didi

python datetime.date 与 SQL 日期不匹配

转载 作者:太空宇宙 更新时间:2023-11-03 15:41:10 25 4
gpt4 key购买 nike

我有一些数据,我想插入到 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()

关于python datetime.date 与 SQL 日期不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42108501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com