BufBills
BufBills

Reputation: 8103

Python SQL statement with variables, using psycopg2 library

 cur.execute('UPDATE newslib SET (keyword1) = %s WHERE id= %s' % m_k1,row[0])

I use psycopg2 to execute this SQL statement. m_k1 and row[0] are two variables I want to pass into the statement.

This triggers the following error message:

TypeError: not enough arguments for format string

I’ve been looking for solutions online, but I can’t fix it.

Upvotes: 1

Views: 1572

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174622

You need to pass the substitutions as arguments to execute. The way you have it written now you have specified two place holders, but did not provide their values, instead you are parsing them in the query itself.

cur.execute('UPDATE newslib SET (keyword1) = %s WHERE id= %s' , (m_k1,row[0],))

Upvotes: 2

falsetru
falsetru

Reputation: 369134

Pass the parameter as a sequence (instead of multiple individual values). And use parameters argument instead of formatting sql yourself.

cur.execute('UPDATE newslib SET (keyword1) = %s WHERE id= %s', [m_k1,row[0]])
#                                                            ^^^^^^^^^^^^^^^

See Cursor.execute

Upvotes: 2

Related Questions