2015-07-20 41 views
1

我想確定將數據從python列表插入到PostgreSQL表中的最簡單方法。如何將python列表插入到Postgres表中

我的PostgreSQL表創建如下;

CREATE TABLE results(Id serial primary key, T0 timestamp, T1 real, T2 real, T3 real, T4 real, Total real, Result text); 

我的python列表的格式如下;

ResultsList = ['2015-07-20 16:06:05', 0.16, 5.22, 5.81, 0.69, 11.90, 'OK'] 

我正在使用下面的python代碼將列表寫入結果表;

import psycopg2 as dbapi 
con = dbapi.connect(database='xxx', user='xxx') 
cur = con.cursor() 
cur.execute("INSERT into results VALUES (%s);", (ResultsList),) 
con.commit() 

解釋器吐出以下錯誤;

Error not all arguments converted during string formatting 
Process finished with exit code 0 

任何線索,將不勝感激。

謝謝:)

+0

很確定這裏有一個python語法錯誤,跟着逗號 – Eric

回答

0

由於ResultList已經是一個序列,你不必試圖將其轉換爲一個元組。你真正需要的是指定在SQL語句中值適量:

cur.execute("INSERT into results(T0, T1, T2, T3, T4, Total, Result) VALUES (%s, %s, %s, %s, %s, %s, %s)", ResultList) 

更多關於它,閱讀the docs

+1

這是行不通的。您需要指定列名稱,否則它將從ID列開始。 –

+0

這不起作用。您必須指定列名稱。 – liushuaikobe

+0

@DanielePantaleone我們需要這個,因爲不是所有的人都被指定了,對吧?否則,我們可以忽略它們。 –

-1

加載多個VALUES從列表到PostgreSQL表。 我還展示瞭如何通過python連接到postgres數據庫,並在postgres中創建一個表。

list_1=[39,40,41,42,43] #list to load in postgresql table 


conn=psycopg2.connect(database="t2_reporting_tool_development",user="xyz",host="localhost") 
cur = conn.cursor() 
cur.execute("create table pg_table (col1 int)") 

#LOADING dealers_list IN pg_table TABLE 
cur.execute("TRUNCATE TABLE pg_table") 
for ddeci in dealers_list: 
    cur.execute("INSERT into pg_table(col1) VALUES (%s)", [ddeci])