Python SQLite parameter substitution with wildcards in LIKE

你离开我真会死。 提交于 2019-11-26 08:56:40

问题


I am attempting to use a parametrized LIKE query with Python\'s Sqlite library as below:

self.cursor.execute(\"select string from stringtable where string like \'%?%\' and type = ?\", (searchstr,type))

but the ? inside of the wildcard is not being evaluated leaving me with this error:

\"sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 2 supplied.\"

I also tried to use the tagged version of querying with:

like \'%:searchstr%\' and in the list having {\"searchstr\":searchstr...

but when I do that the query runs but never returns any results even though manually putting in \"like \'%a%\'\"... return hundreds of results as it should

any suggestions please?


回答1:


The quotes protect either ? or :name from being taken as a place-holder -- they're taken literally. You need to place the percent signs around the string you're passing, and use the plain placeholder without quotes. I.e.:

self.cursor.execute(
  "select string from stringtable where string like ? and type = ?",
  ('%'+searchstr+'%', type))

Note that neither ? is in quotes -- and that's exactly as it should be for them to be taken as placeholders.



来源:https://stackoverflow.com/questions/3105249/python-sqlite-parameter-substitution-with-wildcards-in-like

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!