pythonpostgresqlpsycopg2pg8000

PostgreSQL with pg8000 - INSERT results from an SQL to another table


I am trying to copy rows form a PostgreSQL table to another one, using pg8000 driver for Python. This is the code:

import pg8000
conn = pg8000.connect(user="postgres", password="XXXXX",database="test")
cursor = conn.cursor()
cursor.execute("SELECT * FROM exampletable")
results = cursor.fetchall()

What I want now is to completely insert the results to a new table. It should be something like:

cursor.executemany("INSERT INTO secondtable VALUES (%s)", results)

but is not functioning this way and I don't know how to fix it. Not all fields are of string type, maybe that's should be fixed somehow?


Solution

  • the format %s is for scalar values. Convert results into a string, like this:

    cursor.execute("INSERT INTO secondtable VALUES %s" % str(results))