How to escape % in a query using python's sqlalchemy's execute() and pymysql?

后端 未结 2 1275
独厮守ぢ
独厮守ぢ 2020-12-30 00:56

My query is:

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

gives the

相关标签:
2条回答
  • 2020-12-30 01:15

    Another way to implement bound parameters:

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

    or even typed strictly:

    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%"}
    )
    

    Bear in mind that text() construct is deprecated sine SQLAlchemy 1.4 and will be removed in SQLAlchemy 2.0.

    0 讨论(0)
  • 2020-12-30 01:18

    Since this is a literal string, you're better off using a bound parameter here (illustrated using text()):

    from sqlalchemy import text
    
    connection.execute(
        text("select * from table where "
             "string like :string limit 1"), 
        string="_stringStart%")
    
    0 讨论(0)
提交回复
热议问题