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

时间:2015-09-07 00:38:53

标签: python mysql python-2.7 escaping mysql-python

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仍然拒绝它。所以我加倍 - 撇开撇号,然后插入成功。事实是,它包含转义字符(所以写的是' 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

1 个答案:

答案 0 :(得分:4)

你永远不应该那样构造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)