使用 like with python 和 mysql 连接器编写查询

Writing a query using like with python and mysql connector

如何使用 mysql 连接器和 python 编写查询。我试图避免 sql 注入并且使用 ORM 不是一个选项。

       param = 'bob'
       select_query = mysql_conn.query_db("select * from table_one where col_name like '%?%' order by id asc limit 5", param)

无论我在执行查询时发送什么,我都会得到相同的结果。我应该一无所获。

当我使用以下查询时出现错误。

        select_query = mysql_conn.query_db("select * from table_one where col_name like %s order by id asc limit 5", param)

您的 SQL 语法有误;查看与您的 MySQL 服务器版本相对应的手册,了解在第 1

行的“%s order by id asc limit 5”附近使用的正确语法

Note that any literal percent signs in the query string passed to execute() must be escaped, i.e. %%

http://mysql-python.sourceforge.net/MySQLdb.html

这与旧式 python 字符串格式、c printf 等几乎相同

您需要在转义之前将 % 通配符添加到要传递的 param 中,例如:

select_query = mysql_conn.query_db(
    "select * from table_one where col_name like %s order by id asc limit 5",
     ("%{}%".format(param),)
)

此外,参数应该像上面那样作为元组传递,或者在使用命名参数时作为字典传递:

select_query = mysql_conn.query_db(
    "select * from table_one where col_name like %(p)s order by id asc limit 5",
     {"p": "%{}%".format(param)}
)

You need to add the % wildcards to the param you're passing before escaping, e.g like this:

select_query = mysql_conn.query_db( "select * from table_one where col_name like %s order by id asc limit 5", ("%{}%".format(param),) )

给我一个错误提示

TypeError: a bytes-like object is required, not 'tuple'

所以对我有用的是将引号明确编码到选择引用中,如下所示:

  "select * from table_one where col_name like \"%"+param+"%\" order by id asc limit 5"