如何处理 MySQL-Python 中的撇号?

How to handle apostrophes in MySQL-Python?

A Python API 正在回馈 u"'HOPPE'S No. 9'" 作为特定产品属性的值。然后我想将它插入数据库,也使用 Python (python-mysqldb),查询如下:

INSERT INTO mytable (rating, Name) VALUES('5.0 (7)', 'HOPPE'S No. 9';

MySQL 拒绝这种做法,建议在 MySQL 中处理单引号的方法是 escape it first。我需要在 Python 中完成,所以我尝试:

In [5]: u"'HOPPE'S No. 9'".replace("'", "\'")
Out[5]: u"'HOPPE'S No. 9'"

当我将它合并到我的程序中时,MySQL 仍然拒绝它。所以我 double-转义撇号,然后插入成功。问题是,它包含转义字符(所以写的是 'HOPPE\'S No. 9')。

如果我需要第二个转义字符,但是当我添加它时它被留在里面,那么我如何处理转义而不让转义字符包含在得到的字符串中插入了吗?

编辑: 根据 theBjorn 的建议,尝试了:

actualSQL = "INSERT INTO %s (%s) VALUES(%s);"

#cur.execute(queryString)
cur.execute(actualSQL,
            (configData["table"], sqlFieldMappingString, sqlFieldValuesString))

但看起来我回到了我试图使用 .replace():

的单一转义逃脱时的状态
Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''mytable' ('rating, Name, Image, mfg, price, URL') VALUES('\'5.0 (3)\', \'AR-1' at line 1

你永远不应该那样构造 sql。改为使用参数化代码:

cursor.execute(
    "insert into mytable (rating, name) values (%s, %s);",
    ("5.0 (7)", "HOPPE'S No. 9")
)

你最近的问题是由于误解这是字符串插值,它不是(%s 的使用令人困惑),因此:

actualSQL = "INSERT INTO %s (%s) VALUES(%s);"

会错的。可以构建 sql 字符串,但分两步可能更容易,因此我们不会绊倒看起来像字符串插值标记的 sql 参数标记。假设您在名为 field_values:

的元组中有值
params = ["%s"] * len(field_values)         # create a list with the correct number of parameter markers
sql = "insert into %s (%s) values (%s)" % ( # here we're using string interpolation, but not with the values
    configData["table"], 
    sqlFieldMappingString,
    ', '.join(params)
)

如果你 print sql 它应该看起来像我上面的例子。现在你可以执行它:

cursor.execute(sql, field_values)