PostgreSQL TypeError: not all arguments converted during string formatting

I am executing a query in psycopg2 related to a PostgreSQL database. Here is the code in question:

with open('dataFile.txt', 'r') as f: lines = f.readlines() newLines = [line[:-1] for line in lines] curr=conn.cursor() lineString = ','.join(newLines) curr.execute("SELECT fields.fieldkey FROM fields LEFT JOIN zone ON zone.fieldkey=fields.fieldkey WHERE zone.zonekey = %s;", (newLines[0])) rows = curr.fetchall() 

There is no problem connecting to the database, and the string type [0] is definitely a string, I checked this. Is there something wrong with the syntax of my string formatting?

The error I get to clear this up is:

 TypeError: not all arguments converted during string formatting 
+6
source share
1 answer

There must be a comma after lines[0] to make this a tuple.

 curr.execute(""" SELECT fields.fieldkey FROM fields LEFT JOIN zone ON zone.fieldkey=fields.fieldkey WHERE zone.zonekey = %s; """, (lines[0],)) 

Since the execute method expects a sequence (or display) , it iterates over the line you provided, surrounded by parentheses. Therefore, you must explicitly make this a tuple. The same result with clearer code can be used with the tuple function:

 (tuple(lines[0])) 
+12
source

Source: https://habr.com/ru/post/955922/


All Articles