Reputation: 99
I want to insert a list of values to a Postgres table through Python:
The values are in a list say:
new=
[
[gold, dresden, 1000, 24],
[silver, Cologne, 600, 42],
[gold, Aachen, 3000, 25]
]
And the table has already been created in Postgres with the headers. How do I do the insertion?
db.execute("INSERT INTO B4_O (position, city, amount, score) VALUES (%s,%s,%s)", new)
db.commit
But this gives me error:
not all arguments converted during string formatting
Upvotes: 3
Views: 495
Reputation: 121504
Use psycopg2.extras.execute_values():
new = [
['gold', 'dresden', 1000, 24],
['silver', 'Cologne', 600, 42],
['gold', 'Aachen', 3000, 25]
]
from psycopg2.extras import execute_values
execute_values(db, "INSERT INTO B4_O (position, city, amount, score) VALUES %s", new)
Upvotes: 2
Reputation: 6863
The interface db.execute()
you are using is executing a SQL INSERT command. You can refer to the relevant documentation; you need a string of the form
INSERT INTO B4_O (position, city, amount, score)
VALUES ("gold", "dresden", 1000, 24),
("silver", "Cologne", 600, 42),
("gold", "Aachen", 3000, 25)
A simple way to get the values in python is:
','.join(['("{}", "{}", {}, {})'.format(*x) for x in new])
Note that some python lib like SQLAlchemy support multiple rows insertion out of the box.
Upvotes: 1