PostgreSQL TypeError: not all arguments converted during string formatting

淺唱寂寞╮ 提交于 2020-12-29 11:59:38

问题


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

回答1:


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]))


来源:https://stackoverflow.com/questions/19365072/postgresql-typeerror-not-all-arguments-converted-during-string-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!