[Tutor] SQLite LIKE question
Simone
simozack at yahoo.it
Fri Apr 11 11:53:13 CEST 2008
Dinesh B Vadhia ha scritto:
> The second problem is that I'm using the LIKE operator to match a
> pattern against a string but am getting garbage results. For example,
> looking for the characters q='dog' in each string the SELECT statement
> is as follows:
>
> for row in con.execute("SELECT <column> FROM <table> WHERE <string> LIKE
> '%q%' limit 25"):
> print row
>
> This doesn't work and I've tried other combinations without luck! Any
> thoughts on the correct syntax for the LIKE?
In Python the symbol '%' in a string is a special char: you use it, for
instance, to place a variable inside a string.
The command you need is something like this:
query = "SELECT <column> FROM <table> WHERE <string> LIKE '%s'" % q
for row in con.execute(query):
print row
where q is your variable and %s tells Python that the q variable has to
be converted in a string during the string valorization.
If you want that q contains the symbol '%', you have to escape it by
inserting 2 '%'.
In your example, q have to be 'dog%%' instead of 'dog%'.
However, as Alan said, the method with the question mark to construct
the query is more safe than this.
Hope that helps,
Simone
Chiacchiera con i tuoi amici in tempo reale!
http://it.yahoo.com/mail_it/foot/*http://it.messenger.yahoo.com
More information about the Tutor
mailing list