2016-05-10 29 views
0

數據導入postgres的表我有一個元組,如下值錯誤,同時使用psycopg2

data = ({'weather station name': 'Substation', 'wind': '6 km/h', 'barometer': '1010.3hPa', 'humidity': '42%', 'temperature': '34.5 C', 'place_id': '001D0A00B36E', 'date': '2016-05-10 09:48:58'}) 

我試圖使用下面的代碼從上述元組到postgres的表推值:

try:                                                   
    con = psycopg2.connect("dbname='WeatherForecast' user='postgres' host='localhost' password='****'")                           
    cur = con.cursor()                                                 
    cur.executemany("""INSERT INTO weather_data(temperature,humidity,wind,barometer,updated_on,place_id) VALUES (%(temperature)f, %(humidity)f, %(wind)f, %(barometer)f, %(date)s, %(place_id)d)""", 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() 

凡在DB的每個字段的數據類型的是如下: ID序列NOT NULL,

temperature double precision NOT NULL, 
humidity double precision NOT NULL, 
wind double precision NOT NULL, 
barometer double precision NOT NULL, 
updated_on timestamp with time zone NOT NULL, 
place_id integer NOT NULL, 

當我運行代碼將數據推入postgres表使用psycopg2,它是引發一個錯誤"ValueError: unsupported format character 'f'"

我希望問題是在格式。現在用Python3.4

回答

0

看看在documentation

The variables placeholder must always be a %s , even if a different placeholder (such as a %d for integers or %f for floats) may look more appropriate:

>>> cur.execute("INSERT INTO numbers VALUES (%d)", (42,)) # WRONG 
>>> cur.execute("INSERT INTO numbers VALUES (%s)", (42,)) # correct 

雖然,你的SQL查詢中包含所有類型的佔位符:

"""INSERT INTO weather_data(temperature,humidity,wind,barometer,updated_on,place_id) 
    VALUES (%(temperature)f, %(humidity)f, %(wind)f, %(barometer)f, %(date)s, %(place_id)d)""" 
+0

我試圖改變所有的佔位符爲%s。但是我收到TypeError:元組索引必須是整數,而不是str。 – Harnish

+0

你在'dict'中的所有數據都是字符串格式,例如「風」:'6公里/小時',而你期望'風雙精度非空',這是一個雙重價值。你首先需要編寫一個轉換器,它將顯式格式化你在數據庫中應該輸入的數據,然後到插入位的postgres。 – AKS

+0

嗯,我改變字段數據類型是字符變化。現在我嘗試將所有佔位符更改爲%s。仍然錯誤「TypeError:元組索引必須是整數,而不是str」。保持不變。 – Harnish