psycopg2 TypeError:在字符串格式化期间不是所有参数都被转换

kon*_*art 11 python trac psycopg2

我正在尝试执行一个简单的查询,但无论我如何传递参数,都会收到此错误.

这是查询(我使用Trac db对象连接到DB):

cursor.execute("""SELECT name FROM "%s".customer WHERE firm_id='%s'""" % (schema, each['id']))
Run Code Online (Sandbox Code Playgroud)

schema和每个['id']都是简单的字符串

print("""SELECT name FROM "%s".customer WHERE firm_id='%s'""" % (schema, each['id']))
Run Code Online (Sandbox Code Playgroud)

结果: SELECT name FROM "Planing".customer WHERE firm_id='135'

有错误是删除后引用firm_id=,但该方式参数被视为一个整数,并::text导致相同的错误.

Spe*_*ton 17

就我而言,我没有意识到您必须将一个元组传递给cursor.execute。我有这个:

cursor.execute(query, (id))
Run Code Online (Sandbox Code Playgroud)

但是我需要通过一个元组

cursor.execute(query, (id,))
Run Code Online (Sandbox Code Playgroud)

  • 这是世界上最愚蠢的事情。在我曾经在任何编程语言中使用过的所有模块中,这一定是我所见过的最荒唐的陷阱之一。他们必须先随机插入一个逗号(转换为元组),才能完成这项工作? (8认同)
  • 顺便说一句,即使我的输入是元组,我仍然必须将其转换为元组(因此是元组的元组)。同意@NateL - 这太糟糕了 (2认同)
  • Python 处于最佳状态!讨厌这条蛇。 (2认同)

rsa*_*acc 10

我得到了同样的错误,并且在我的生活中无法解决如何修复,最终这是我的愚蠢错误,因为我没有足够的参数匹配元组中的元素数量:

con.execute("INSERT INTO table VALUES (%s,%s,%s,%s,%s)",(1,2,3,4,5,6))
Run Code Online (Sandbox Code Playgroud)

请注意,我在要插入表中的值中有5个元素,但在元组中有6个元素.

  • 谢谢!这个观察帮助我检查并发现我做了类似愚蠢的事情!:) (2认同)

小智 7

你可以试试这个:

cursor.execute("INSERT INTO table_name (key) VALUES(%s)",(value1,))
Run Code Online (Sandbox Code Playgroud)

如果缺少(,)after ,您将收到错误value1


ndp*_*dpu 5

在 SQL 命令中传递变量的正确方法是使用该execute()方法的第二个参数。我认为您应该从第二个参数中删除单引号,请在此处阅读 - http://initd.org/psycopg/docs/usage.html#the-problem-with-the-query-parameters

请注意,您不能将表名作为参数传递给execute,这被认为是不好的做法,但有一些解决方法:使用 SQL 查询参数
将表名作为参数传递到 psycopg2
psycopg2cursor.execute() 会导致语法错误

要传递表名称,请尝试以下操作:

cursor.execute("""SELECT name FROM "%s".customer WHERE firm_id=%s""" % (schema, '%s'), (each['id'],))
Run Code Online (Sandbox Code Playgroud)


RjO*_*los 5

您不应该使用字符串插值来传递数据库查询中的变量,但使用字符串插值来设置表名是正常的(只要它不是外部输入或限制允许值).尝试:

cursor.execute("""SELECT name FROM %s.customer WHERE firm_id=%%s""" % schema, each['id'])
Run Code Online (Sandbox Code Playgroud)

在对数据库进行编程之前,应该要求读取DB API使用规则.


Clo*_*eto 5

AsIs

from psycopg2.extensions import AsIs

cursor.execute("""
    select name 
    from %s.customer 
    where firm_id = %s
    """, 
    (AsIs(schema), each['id'])
)
Run Code Online (Sandbox Code Playgroud)