Python将u"'HOPPE'S No. 9'"
作为特定产品属性的值返回。然后,我将使用Python (Python)将其插入到DB中,并使用以下查询:
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仍然拒绝它。因此,我双-escape撇号,然后插入成功。问题是,它包含转义字符(因此编写的是'HOPPE\'S No. . 9')。
如果我需要第二个转义字符,但当我将它添加到其中时,我如何处理转义,而不将转义字符包含在插入的字符串中?
编辑:基于Based的建议,尝试了:
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
发布于 2015-09-07 00:44:06
您不应该以这种方式构造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)
https://stackoverflow.com/questions/32429702
复制相似问题