Python SQL DB string literals and escaping

一笑奈何 提交于 2019-12-13 15:23:57

问题


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




回答2:


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



来源:https://stackoverflow.com/questions/4189808/python-sql-db-string-literals-and-escaping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!