Python SQL DB字符串文字和转义

问题描述:

有人知道MySQLdb是否会自动转义SQL语句的字符串文字吗?

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.

在第一个示例中没有转义,它是原始SQL查询.这是有效的,它将起作用,但是显然,只有在您始终要搜索帐户Blah时,它才有意义.

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.

当需要从变量中的名称获取帐户时,将需要参数化的版本.但是,您的示例可能无法正常工作,因为(x) 不是元组,而只是值x.元组序列中的x将是(x,).为避免混淆,您可能更喜欢使用列表[x].

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