MySQL Python LIKE通配符

use*_*003 10 python mysql

我想做一个Python MySQL查询,例如:

cursor = connection.cursor()
sql = "select text \
       from steps \
       where text like '%start%'"
cursor.execute(sql)
Run Code Online (Sandbox Code Playgroud)

但我认为%不被视为通配符,它​​期待变量.我收到一个错误:

TypeError: not enough arguments for format string
Run Code Online (Sandbox Code Playgroud)

似乎没什么用.如果我可以使用变量而不是'%start%'那也很好

sou*_*eck 20

我假设您正在使用python db-api.

您可以尝试转义%%%.

至于传递参数,有很多种方法,例如:

cursor = connection.cursor()
sql = """select text 
   from steps 
   where text like %s"""
cursor.execute(sql, (('%' + 'start' + '%',))
Run Code Online (Sandbox Code Playgroud)

您可以在"Interfacemodułu"部分中查看此博客上其他参数传递方式的示例.并非所有连接器都适用.

  • 与%%的转义工作,谢谢:)使用文字字符串给出了相同的错误. (2认同)
  • 传递参数不起作用。我没有收到错误,但它找到 0 行,让我认为它没有看到通配符。这有效:sql =“从cmt_steps中选择文本,其中文本如'%%”+start+“%%'” (2认同)