0

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?

1
  • what orm are you using? you should bind parameters to your query instead of concatenating a string.. it opens you to sql injection Commented Jun 8, 2015 at 20:27

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

You just saved my day. Thanks a lot! Owe you one.
@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!
Yup. Did it. Thanks for the suggestion as well. Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.