开发者

Python SQL DB string literals and escaping

开发者 https://www.devze.com 2023-01-25 01:04 出处:网络
Anyone know if the MySQLdb will automatically escape string literals for SQL statements? For instance I am trying to execute the following:

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.开发者_高级运维


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].


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. :-)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号