I am calling SQL in Python and when I try to use a string in SQL it does not consider it as a string because the whole SQL statement in enclosed in "". What should I do?
This is my Python code for SQLl. I just want do_check_id to be considered as a string here.
call.sql("SELECT a.id FROM application a where ed.servicename = 'do_check_id'")
-
That's a fine string. Does it work? If not, what error do you get?user1907906– user19079062014年12月18日 13:40:36 +00:00Commented Dec 18, 2014 at 13:40
-
Show us more code and what you expect...tamasgal– tamasgal2014年12月18日 13:45:14 +00:00Commented Dec 18, 2014 at 13:45
3 Answers 3
If you want to use your do_check_id string variable inside a sql command consider using of placeholders and prepared statements:
Using psycopg2 to interact with Postgres:
cursor.execute("SELECT a.id FROM application a where ed.servicename = %s", do_check_id)
Comments
You may want to try with string formatting as below.
str_val = 'do_check_id'
call.sql("SELECT a.id FROM application a where ed.servicename = %s" %str_val)
2 Comments
format() function: call.sql("SELECT a.id FROM application a where ed.servicename = {0}".format(str_val))% formatter or the .format() method.This depends on your DB driver.
The sqlite3 driver which comes with Python uses ? for this:
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
Other drivers have similar features.
Don't try to build SQL yourself, there are some pitfalls that may make your code vulnerable to SQL injection.