2

Anyone know if the MySQLdb will automatically escape string literals for SQL statements?

For instance I am trying to execute the following:

cursor.execute("""SELECT * FROM `accounts` WHERE `account_name` = 'Blah'""")

Will this escape the account name automatically? Or will it only escape if I do the following?:

x = 'Blah'
cursor.execute("""SELECT * FROM `accounts` WHERE `account_name` = %s""", (x))

Or will it do it for both? Can anyone clarify this as I can't find any information on it.

1
  • There's no point for notation (x). Commented Nov 15, 2010 at 23:34

2 Answers 2

2

There is no escaping in the first example, it is a raw SQL query. It's valid, it'll work, but obviously it only makes sense if you always want to search for account Blah.

When you need to get an account from a name in a variable, you will need the parameterised version. However your example may not work as expected as (x) isn't a tuple, it's just the value x. x in a tuple sequence would be (x,). To avoid confusion you may prefer to use the list [x].

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

Comments

1

Escaping is only done when you give the query and data to MySQLdb separately. That's how it knows what to escape. :-)

Thus, only your 2nd example will escape:

x = ('Blah',)
cursor.execute("""SELECT * FROM `accounts` WHERE `account_name` = %s""", x)

Note how I changed x to to tuple. That is what MySQLdb expects. It sort of makes sense since you may need to pass in multiple variables. Like:

x = ('Blah','Foo23')
cursor.execute("""SELECT * FROM `accounts` WHERE `account_name` = %s OR `account_code` = %s""", x)

Let me know if this answers your question.

Good Luck. :-)

Comments

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.