I want to run a Dynamic query in python.
I have a combobox with 4 values (Direct, Indirect, Intermediary, Pointed). What I want to do is to write a dynamic query to interrogate my database and return the count of items.
I have this code:
(val is used to retrieve the value from a combobox)
c=db.cursor()
val=var.get()
query='SELECT count(*) from table where field=' + val
c.execute(query)
Now the query works if I write it like query='SELECT count(*) from table where field="Direct"' but I want it to work dynamically.
Is there any solution?
asked Jun 8, 2015 at 20:25
Nick Dragosh
5153 gold badges9 silver badges21 bronze badges
-
what orm are you using? you should bind parameters to your query instead of concatenating a string.. it opens you to sql injectionJohn Ruddell– John Ruddell2015年06月08日 20:27:35 +00:00Commented Jun 8, 2015 at 20:27
1 Answer 1
try something like this maybe?
db.execute("SELECT count(*) from table where field = %s", [val])
this is assuming you are using pymssql which uses "%s" to bind parameters
answered Jun 8, 2015 at 20:32
John Ruddell
25.9k7 gold badges60 silver badges88 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Nick Dragosh
You just saved my day. Thanks a lot! Owe you one.
John Ruddell
@NickDragosh glad I could help! this is also a much more secure way of executing a query because if some random user hits your function they could literally destroy your database
query='SELECT count(*) from table where field="' + val + '"' if they made val be val='"; DROP DATABASE;' you would be in trouble :) dont forget to mark the answer as accepted when you have a chance!Nick Dragosh
Yup. Did it. Thanks for the suggestion as well. Cheers!
default