How to execute SELECT * LIKE statement with a placeholder in sqlite?

给你一囗甜甜゛ 提交于 2020-12-26 07:13:09

问题


I've got an argument tag and I perfomed this way:

cursor.execute("SELECT * FROM posts WHERE tags LIKE '%?%'", (tag,))

but it doesn't seem to work.
I'm new to sqlite, please tell me how to fix it. Thx !


回答1:


Apply the wildcards to the parameter, not the SQL:

cursor.execute("SELECT * FROM posts WHERE tags LIKE ?", (f'%{tag}%',))

The ? SQL parameter interpolation adds quoting for you, so your query ends up as '%'value'%', which is not valid SQL.




回答2:


Remove the %:

cursor.execute("SELECT * FROM posts WHERE tags LIKE ?", (tag,))

This should format it as you wanted. For example, if tag == 'test' the full query would be:

SELECT * FROM posts WHERE tags LIKE 'test'


来源:https://stackoverflow.com/questions/20904209/how-to-execute-select-like-statement-with-a-placeholder-in-sqlite

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