2015-07-20 113 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])