Skip to content Skip to sidebar Skip to footer

How To Insert A Python List Into Postgres Table

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 prim

Solution 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.

Solution 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])

Post a Comment for "How To Insert A Python List Into Postgres Table"