在 python 中的 select 语句的 like 子句中使用 %

Using % in like clause of select statement in python

import pypyodbc as pyodbc
model_name = 'test'
model_name1 = Master_Cursor.execute("select col1,col2,col3 from tablename where col3 like '%s' order by col3" %(model_name)).fetchall()

以上代码 returns 一条记录匹配 model_name = test。 我将如何取回具有 model_name=123test123,abctestabc,ABCtestABC 等的其他记录?

基本上是找

select col1,col2,col3 from tablename where col3 like '%test%'.
model_name1 = Master_Cursor.execute("select col1,col2,col3 from tablename where col3 like '%%%s%%' order by col3" %(model_name)).fetchall()

用2个百分号表示一个真正的百分号

不要使用字符串格式将变量插入到您的查询中,这会使您面临 SQL 注入的风险(参见 What is SQL injection?) Instead, and per the documentation,您应该使用 ? 来表示查询中的变量,并让库转义并适当地插入它们。

接下来,如果您想要更宽松的匹配,您需要实际包括通配符和 model_name。目前您正在创建:

select col1,col2,col3 from tablename where col3 like 'test' order by col3

在将 传递到查询之前,您需要用通配符 model_name 括起来,例如使用 '%%%s%%' % model_name(请注意,您需要重复每个 % 以在 printf-style formatting 中转义它)或更现代的字符串格式选项之一。

在这种情况下,例如(使用str.format):

model_name1 = Master_Cursor.execute(
    "select col1, col2, col3 from tablename where col3 like ? order by col3",
    ("%{}%".format(model_name),)
).fetchall()

以下应该有效:

pattern = "%"+model_name+"%"
db.execute("select col1,col2,col3 from tablename where col3 like :s order by col3" ,{"s":pattern}).fetchall()