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
我試圖改變所有的佔位符爲%s。但是我收到TypeError:元組索引必須是整數,而不是str。 – Harnish
你在'dict'中的所有數據都是字符串格式,例如「風」:'6公里/小時',而你期望'風雙精度非空',這是一個雙重價值。你首先需要編寫一個轉換器,它將顯式格式化你在數據庫中應該輸入的數據,然後到插入位的postgres。 – AKS
嗯,我改變字段數據類型是字符變化。現在我嘗試將所有佔位符更改爲%s。仍然錯誤「TypeError:元組索引必須是整數,而不是str」。保持不變。 – Harnish