db question

B

bruce

Hi...

simple test

mysql cmd - select * from foo where dog like "%small%";

sql ="""select * from foo where dog like "%%%s%%" """
c.execute(sql, (var,))


the above doesn't work, and I can't seem to figure out how to display/print
out the sql as i't actually been excuted, so I can see where the issue is.

i've tried to "/" escape, as well as a few other things, now of which shed
any light on the issue. haven't found any information via google either.

the above works if i have something like
sql="""select * from foo where dog=%s"""
c.execute(sql,(var,))

so.. any help/pointers on what i've screwed up/missed would be helpful.

thanks
 
L

Lawrence D'Oliveiro

Dennis Lee said:
The execute statement is responsible quoting your literals, so the
final statement you end up submitting looks like:

select * from foo where dog like ""%"xxx"%""

or some variant thereof.

Anything parameterized with %s must be a complete term!

Try:

sql = "select * from foo where dog like %s"
c.execute(sql, ("%" + var + "%",) )

IOW: you need to massage the variable search term to include the
wildcard % FIRST, then let MySQLdb substitute it (with surrounding
quotes and escapes) into the SQL.

More general, less pitfall-prone solution:

select * from foo where dog like %s" %
SQLString("%" + EscapeSQLWild("small") + "%")

where SQLString and EscapeSQLWild are defined as in
<http://groups.google.co.nz/group/comp.lang.python/msg/ed7e561036895cbe>.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,141
Latest member
BlissKeto
Top