【发布时间】:2018-02-13 22:59:16
【问题描述】:
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()
上面的代码返回一条匹配model_name = test的记录。
我如何取回具有model_name=123test123,abctestabc,ABCtestABC 等的其他记录?
基本上是在找
select col1,col2,col3 from tablename where col3 like '%test%'.
【问题讨论】:
-
第一件事是不使用字符串格式来创建查询,因为这会使您容易受到 SQL 注入的影响。
-
此外,如果您必须进行字符串格式化,还有比
printf样式更多的最新选项!你的问题的简单答案是stackoverflow.com/q/10678229/3001761,但你真的应该使用适当的变量处理,as documented。 -
猜测:
model_name1 = Master_Cursor.execute("SELECT col1,col2,col3 FROM tablename WHERE col3 LIKE ? ORDER BY col3",(model_name,)).fetchall() -
@roganjosh 是的,我希望看到
... LIKE ?,那么变量中的通配符也将包含%。例如:stackoverflow.com/a/24377191/3001761. -
@roganjosh Python DB API 允许各种参数样式:python.org/dev/peps/pep-0249/#paramstyle。我不知道它是否会因底层数据库而异。