I'm a postgres newbie and am having some issues querying a text field in postgresql using Python. What is the correct syntax that will allow me to search the content of column "body" from table "jivemessage" out of database "postgres"?
try:
conn = psycopg2.connect("dbname='postgres' user='postgres' host='localhost' password='<password>'")
except:
print "cannot connect"
i = 'test'
cur = conn.cursor()
cur.execute('SELECT * from jivemessage WHERE body LIKE "%'+i+'%"')
Keep getting the following error:
ProgrammingError: column "%test%" does not exist
Thanks for any help.
-
if you are searching body like that you may want to look at postgresql's fulltext search index.cmd– cmd2014年01月14日 15:51:33 +00:00Commented Jan 14, 2014 at 15:51
-
You've got your quotes mixed up. the basic for here is: select * from sometable where somefield like '%text%'; Note the SINGLE QUOTES here.Scott Marlowe– Scott Marlowe2014年01月14日 21:57:48 +00:00Commented Jan 14, 2014 at 21:57
1 Answer 1
You are not quoting the query properly. Don't use string concatenation here, use SQL parameters instead:
cur.execute('SELECT * from jivemessage WHERE body LIKE %s', ("%{}%".format(i),))
Here, the %s placeholder signals to the database driver that the first value of the second argument should be placed there when querying.
This leaves the interpolation up to the database driver, giving the database the opportunity to optimize for the query once, even if you were to reuse the same query.
It also prevents SQL injection attacks better than you could yourself, and most of all, guarantees that the correct quoting rules are followed.
7 Comments
psycopg2 wasn't actually binding their variables as I had expected when I started using this library.