python日期时间.日期不匹配SQL d

2024-06-16 11:25:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我得到一些错误:

^{pr2}$

这是表结构:

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日期:日期应与SQL日期匹配。我没有通过搜索stackoverflow得到我想要的答案。那么我该如何解决这个问题呢?在


Tags: infoexecutedatadatetimedatelocationconnweather
1条回答
网友
1楼 · 发布于 2024-06-16 11:25:27

您的问题是您使用字符串格式化运算符%来创建动态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,没有分隔符,因此它被解释为一个整数表达式。在

您需要做的是使用适当的参数化查询

^{pr2}$

或者只是

sql = """\
insert into WEATHER_INFO(location,weather_date,high_tempature,low_tempature,weather,wind)
values(?,?,?,?,?,?)
"""
cur.executemany(sql, data)
conn.commit()

相关问题 更多 >