yakiang
yakiang

Reputation: 1634

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

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 !

Upvotes: 7

Views: 6447

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1125398

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.

Upvotes: 12

aIKid
aIKid

Reputation: 28352

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'

Upvotes: 1

Related Questions