我正在psycopg2中执行一个链接到PostgreSQL数据库的查询。以下是有问题的代码:
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()
连接到DB没有问题,行[0]的类型肯定是字符串,我检查了。我的字符串格式的语法有问题吗?
我得到的错误,澄清的是:
TypeError: not all arguments converted during string formatting
答案 0 :(得分:15)
lines[0]
之后必须有逗号才能使其成为元组。
curr.execute("""
SELECT fields.fieldkey
FROM fields
LEFT JOIN zone ON zone.fieldkey=fields.fieldkey
WHERE zone.zonekey = %s;
""", (lines[0],))
由于execute
method is expecting a sequence (or a mapping)它会迭代你用括号括起来的字符串。因此有必要明确地将其作为一个元组。使用tuple
function:
(tuple(lines[0]))