psycopg2 how deal with TypeError: not all arguments converted during string formatting

Question:

I have this code:

ip = "127.0.0.1"
sql = "select count(*) from radacct where nasipaddress=%s"
cur.execute(sql,ip)

But I get an error like

TypeError: not all arguments converted during string formatting

How can i pass the parameters to psycopg2 in the correct way?

Asked By: zzlettle

||

Answers:

The sql arguments you pass to execute must be in a tuple or list, even if there’s only one of them. This is noted in the documentation:

For positional variables binding, the second argument must always be a
sequence, even if it contains a single variable. And remember that
Python requires a comma to create a single element tuple:

So you need to do it like this:

ip ="127.0.0.1" 
sql="select count(*) from radacct where nasipaddress=%s"
cur.execute(sql, (ip,))
Answered By: dano
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.