如何将 python 列表插入 Postgres table
How to insert a python list into Postgres table
我正在尝试确定将数据从 python 列表插入 PostgreSQL table 的最简单方法 table。
我的 PostgreSQL table 创建如下;
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 代码将列表写入结果 table;
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
如有任何线索,我们将不胜感激。
谢谢:)
因为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。
将列表中的多个值加载到 PostgreSQL TABLE。
我还展示了如何通过 python 连接到 postgres 数据库并在 postgres 中创建一个 table。
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])
我正在尝试确定将数据从 python 列表插入 PostgreSQL table 的最简单方法 table。
我的 PostgreSQL table 创建如下;
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 代码将列表写入结果 table;
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
如有任何线索,我们将不胜感激。
谢谢:)
因为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。
将列表中的多个值加载到 PostgreSQL TABLE。 我还展示了如何通过 python 连接到 postgres 数据库并在 postgres 中创建一个 table。
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])