Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL TypeError: not all arguments converted during string formatting

I am executing a query in psycopg2 linked up 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's no issue connecting to the DB, and the type of lines[0] is definitely string, I checked that. Is there something wrong in the syntax of my string formatting?

The error I get, to clarify is this:

TypeError: not all arguments converted during string formatting
like image 939
Alex Chumbley Avatar asked Oct 14 '13 16:10

Alex Chumbley


People also ask

How do you fix not all arguments converted during string formatting?

Such a common error is TypeError: not all arguments converted during string formatting. This error is caused when there is a mismatch in data types and strings are not properly formatted. The solution to this error is to use proper string formatting functions such as int() or str() to obtain the desired data type.

What does it mean not all arguments converted during string formatting?

The “not all arguments converted during string formatting” error is raised when Python does not add in all arguments to a string format operation. This happens if you mix up your string formatting syntax or if you try to perform a modulo operation on a string.

What does %s mean in Python?

%s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string. It is used to incorporate another string within a string. It automatically provides type conversion from value to string.

How do you check a string format in Python?

Use time. strptime to parse from string to time struct. If the string doesn't match the format it raises ValueError . Show activity on this post.


1 Answers

There must be a comma after lines[0] to make that 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 is expecting a sequence (or a mapping) it iterates over the string you provided surrounded by parenthesis. So it is necessary to explicitly make that a tuple. The same result, with clearer code, can be had using the tuple function:

(tuple(lines[0]))
like image 159
Clodoaldo Neto Avatar answered Oct 13 '22 10:10

Clodoaldo Neto