如何在Postgres表中插入python列表

时间:2015-07-20 07:31:09

标签: python postgresql psycopg2

我正在尝试确定将数据从python列表插入PostgreSQL表的最简单方法。

我的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

任何线索都会受到赞赏。

谢谢:)

2 个答案:

答案 0 :(得分: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 :(得分:-1)

将一个列表中的多个值加载到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])
相关问题