Reputation: 105
data = [2, 5.5, 'Harry Potter']
statement = "INSERT INTO ranks (Rank, Height, Name) values(%s, %s, %s)"
#made a connection to a postgres database using psycopg2
I want to pass the list named data
as a parameter to the cursor.execute()
function used to execute the statement.
Note : As the the
data
list contains elements with different data types, I cannot use the string.join() method on it.
How should I do that?
Upvotes: 0
Views: 1272
Reputation: 19590
See here.
Basically:
cur.execute(statement, data)
So pass a sequence of values to the query that will match the %s
parameters in order.
UPDATE. Doing:
create table ranks (rank integer, height numeric, name varchar);
import psycopg2
con = psycopg2.connect("dbname=test host=localhost user=aklaver")
data = [2, 5.5, 'Harry Potter']
statement = "INSERT INTO ranks (Rank, Height, Name) values(%s, %s, %s)"
cur = con.cursor()
cur.execute(statement, data)
con.commit()
select * from ranks ;
rank | height | name
------+--------+--------------
2 | 5.5 | Harry Potter
works. So your error must be with some other data or statement.
Upvotes: 1