【问题标题】:How to escape % in a query using python's sqlalchemy's execute() and pymysql?如何使用 python sqlalchemy execute() 和 pymysql 在查询中转义 %?
【发布时间】:2019-12-31 12:00:07
【问题描述】:

我的查询是:

result = connection.execute(
         "select id_number from Table where string like '_stringStart%' limit 1;")

给出错误:

query = query % escaped_args
TypeError: not enough arguments for format string

一个快速的谷歌说使用 %% 而不是 % 但这也不起作用。如何转义 % 或者是否有另一种方法来查询以随机字母开头然后以特定序列开头的字符串?

【问题讨论】:

    标签: python mysql sqlalchemy


    【解决方案1】:

    由于这是一个文字字符串,因此最好在此处使用绑定参数(使用text() 说明):

    from sqlalchemy import text
    
    connection.execute(
        text("select * from table where "
             "string like :string limit 1"), 
        string="_stringStart%")
    

    【讨论】:

    • 嗨~,如何与sqlalchemy orm一起使用?
    • @DachuanZhao session.query.filter(table.string.like('_stringStart%'))
    • @bfontaine 为什么要逃避百分比?它与答案中的示例完全相同。 ORM 已经使用绑定参数。内部 sqlalchemy 代码不(或不再)使用带有 '%' 字符串扩展的查询,这是原始错误。
    • @wolfmanx 抱歉,我误解了这个问题。我认为这是关于转义 % 以便 *SQL 不会解释它,而它是关于转义 Python 本身。我删除了我的评论。
    【解决方案2】:

    实现绑定参数的另一种方式:

    from sqlalchemy import text
    
    connection.execute(
        text("select id_number from Table where string like :string limit 1").\
        bindparams(string="_stringStart%")
    )
    

    甚至严格输入:

    from sqlalchemy import bindparam, String, text
    
    connection.execute(
        text("select id_number from Table where string like :string limit 1").\
        bindparams(bindparam("string", type_=String)),
        {"string"="_stringStart%"}
    )
    

    请记住,text() 构造在 SQLAlchemy 1.4 中已被弃用,并将在 SQLAlchemy 2.0 中删除。

    【讨论】:

    猜你喜欢
    • 2013-02-03
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 2023-01-16
    • 2015-09-26
    • 2019-09-29
    • 2021-07-21
    相关资源
    最近更新 更多