问题
I am trying to determine the simplest way to insert data from a python list into a PostgreSQL table.
My PostgreSQL table was created as follows;
CREATE TABLE results(Id serial primary key, T0 timestamp, T1 real, T2 real, T3 real, T4 real, Total real, Result text);
My python list is formatted as follows;
ResultsList = ['2015-07-20 16:06:05', 0.16, 5.22, 5.81, 0.69, 11.90, 'OK']
I am using the following python code to write the list into the results 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()
The interpreter spits out the following error;
Error not all arguments converted during string formatting
Process finished with exit code 0
Any clues would be appreciated.
Thanks :)
回答1:
As ResultList
is already a sequence, you do not need to try and convert it to a tuple. What you really need is specify the right amount of values in your SQL statement:
cur.execute("INSERT into results(T0, T1, T2, T3, T4, Total, Result) VALUES (%s, %s, %s, %s, %s, %s, %s)", ResultList)
For more about it, read the docs.
回答2:
LOADING MULTIPLE VALUES FROM A LIST INTO A POSTGRESQL TABLE. I have also shown how to connect to a postgres database through python and create a table in 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])
来源:https://stackoverflow.com/questions/31510945/how-to-insert-a-python-list-into-postgres-table