Python/MySQL组合的最佳转义字符策略是什么?

Thi*_*ode 5 python mysql escaping

这是我的查询.

cursor2.execute("update myTable set `"+ str(row[1]) +"` = \"'" + str(row[3]) +"'\" where ID = '"+str(row[0])+"'")
Run Code Online (Sandbox Code Playgroud)

当行值具有双引号"某个值"时失败.如何逃脱所有特殊角色?

Man*_*dan 13

这是一个例子:

import MySQLdb
column = str(MySQLdb.escape_string(row[1]))
query = "update myTable set %(column)s = %%s where ID = %%s" % dict(column = column) 
cursor2.execute(query, [row[3], row[0]])
Run Code Online (Sandbox Code Playgroud)

更新

这是一个简短的评论:

column = str(MySQLdb.escape_string(row[1]))
Run Code Online (Sandbox Code Playgroud)

总是一个好主意来逃避任何进入查询的东西.在这种情况下,我们动态添加列名,因此必须在执行查询之前对其进行转义.

query = "update myTable set %(column)s = %%s where ID = %%s" % dict(column = column) 
Run Code Online (Sandbox Code Playgroud)

我在这里形成查询.我试图实现两件事:(1)使用column上一行中声明的变量填充列名称的查询(2)添加占位符,这些占位符将在查询执行期间由实际参数填充.

该片段dict(column = column)实际上是创建字典的另一种方式{'column': column}.使用dict构造函数可以实现这一点.我还不想填写其他占位符,所以我使用两个百分号(%%)来逃避它们.

cursor2.execute(query, [row[3], row[0]])
Run Code Online (Sandbox Code Playgroud)

最后执行查询.如果在执行之前打印查询,则会看到字符串update myTable set column_name = %s where ID = %s.


zne*_*eak 7

对于值,您应该使用准备好的查询来嵌入它们.对于行,我不太确定......这取决于你的设置.您可能希望接受ASCII值32以上的任何字符,除非未转义的反引号.但是,不要认为这有一个特定的功能.

cursor2.execute("UPDATE myTable SET `" + str(row[1]) + "` = ? WHERE ID = ?", (row[3], row[1]))
Run Code Online (Sandbox Code Playgroud)

准备好的查询有问号,应该有变量,并且您将列表或元组作为第二个参数传入,以指定它们应该替换的内容.司机将负责确保价值安全.但是,您只能将询问标记放在预期值的位置; 所以你不能将它们用作列名.


Bil*_*win 7

您应该学会使用查询参数:

colname = str(row[1]).replace("`", "\\`")
sql = "update myTable set `%s` = :col1 WHERE ID = :id" % (colname)
cursor2.execute(sql, {"col1":str(row[3]), "id":str(row[0])})
Run Code Online (Sandbox Code Playgroud)