3

I am trying to do the following query:

cursor.execute("SELECT DISTINCT(provider) FROM raw_financials 
                WHERE vendor_id="%s" OR title='%'", (vendor_id, title))

My problem is that the title can be anything, for example it can be "Hello, Sir", 'Yes' he responded. So when I do the above, I could get a (bad) return value, such as An Elf\\'s Story (which raises a SQL error).

How would I correctly quote the SQL statement and the title here?

1
  • Depends on the database, some want backslashes (A\'B), some want doubled-quotes (A''B), etc... Commented Jan 19, 2012 at 22:29

1 Answer 1

5

Don't quote it yourself; your DB driver will do it for you:

cursor.execute("SELECT DISTINCT(provider) FROM raw_financials 
            WHERE vendor_id = %s OR title = %s", (vendor_id, title))

Edit: Above, %s are placeholders which indicate where the arguments (vendor_id and title) should be inserted. MySQLdb uses %s for placeholders, but some other drivers use ?. You may have to change my code above to use the placeholder appropriate for your driver.

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

2 Comments

Shouldn't be ? instead of %s?
It depends on the driver. sqlite3 and oursql use ?, while MySQLdb uses %s placeholders. Thanks for reminding me that my answer was (unwittingly) MySQLdb-specific.

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.