使用psycopg2向postgresql表添加数据时出错

时间:2016-05-11 13:39:36

标签: django postgresql python-3.x psycopg2

我有一个元组

final_weather_data = ({'date': '2016-05-11 13:22:58', 
  'place_id': '001D0A00B36E', 'barometer_unit': 'hPa', 
  'weather station name': 'NPCL Hatewa Substation',
  'wind_dir_unit': 'degree', 'temperature': 31.2, 
  'barometer': 1007.9, 'temp_unit': 'C', 'hum_unit': '%', 
  'wind_unit': 'km/h', 'wind_direction': 'NE nbsp 49', 
  'humidity': 60, 'wind_speed': 8.0}) 

我试图通过

将其推入postgres表
try:

con = psycopg2.connect("dbname='WeatherForecast' user='postgres' host='localhost' password='postgres'")
cur = con.cursor()
cur.mogrify("""INSERT INTO weather_data(temperature,temp_unit,humidity,hum_unit,wind,wind_speed_status,wind_unit,wind_dir,wind_dir_unit,barometer,bar_unit,updated_on,station_id) VALUES (%(temperature)s, %(temp_unit)s, %(humidity)s, %(hum_unit)s, %(wind)s, %(wind_speed_status)s, %(wind_unit)s, %(wind_dir)s, %(wind_dir_unit)s, %(barometer)s, %(bar_unit)s, %(updated_on)s, %(station_id)s);""", final_weather_data)
ver = cur.fetchone()
print(ver)


except psycopg2.DatabaseError as e:
  print('Error {}'.format(e))
  sys.exit(1)


finally:

  if con:
    con.close()

当我运行上面的代码时,它引发了一个错误" TypeError:元组索引必须是整数,而不是str"。 相反,如果我尝试这样 我正在关注此https://wiki.postgresql.org/wiki/Psycopg2_Tutorial

2 个答案:

答案 0 :(得分:2)

在你的情况下,final_weather_data是dicts的元组。但是你在查询中使用文本键。它实际上是错误的原因:“TypeError:元组索引必须是整数,而不是str”。

请尝试:

final_weather_data = {
  'date': '2016-05-11 13:22:58', 
  'place_id': '001D0A00B36E', 'barometer_unit': 'hPa', 
  'weather station name': 'NPCL Hatewa Substation',
  'wind_dir_unit': 'degree', 'temperature': 31.2, 
  'barometer': 1007.9, 'temp_unit': 'C', 'hum_unit': '%', 
  'wind_unit': 'km/h', 'wind_direction': 'NE nbsp 49', 
  'humidity': 60, 'wind_speed': 8.0
} 

答案 1 :(得分:0)

This saved me.  
con = psycopg2.connect("dbname='WeatherForecast' user='postgres' host='localhost' password='postgres'")
cur = con.cursor()
fieldnames = ['temperature', 'temp_unit', 'humidity', 'hum_unit', 'wind', 'wind_speed_status', 'wind_unit', 'wind_dir', 'wind_dir_unit', 'barometer', 'bar_unit', 'updated_on', 'station_id']
sql_insert = ('INSERT INTO weather_data (%s) VALUES (%s)' %
              (','.join('%s' % name for name in fieldnames),
               ','.join('%%(%s)s' % name for name in fieldnames)))
cur.executemany(sql_insert, stations_weather_data)