MySQL语句python escape单引号';
我使用python编写了以下MySQL语句,但其中一个值中有一个引号,因此我得到以下错误:MySQL语句python escape单引号';,python,mysql,scrapy,character,mysql-error-1064,Python,Mysql,Scrapy,Character,Mysql Error 1064,我使用python编写了以下MySQL语句,但其中一个值中有一个引号,因此我得到以下错误: 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 L at line 1 要插入的值是Regal INT'L 如何转义或更正MySQL语句 MySQL语句 def query(self,
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 L at line 1
要插入的值是Regal INT'L
如何转义或更正MySQL语句
MySQL语句
def query(self, item):
return "INSERT INTO income_statement({columns}) VALUES ({values})".format(
columns=', '.join(item.keys()),
values=self.item_to_text(item)
)
def item_to_text(self, item):
return ', '.join("'" + str(v) + "'" for v in item.values()
)
返回字符串模板的元组和变量的元组,游标可以执行(模板,(v1,v2,…) 基于 编辑2:一个更完整的示例
def query(self, item):
values = ', '.join(['%s']*len(item.keys()))
stmt = "INSERT INTO income_statement({columns}) VALUES ({values})".format(
columns=', '.join(item.keys()),
values=values
)
# self.item_to_text(item) must be a tuple
return (stmt, self.item_to_text(item))
# use it like so
cursor.execute(query(item))
编辑3:
我非常确定,如果您真的想将语句作为单个字符串传递,那么必须在字符串本身中有一个\ present,从而使用
国际
编辑4:
def item_to_text(self, item):
return ', '.join(item.values()) # assuming item.values() returns a list or a tuple
我还没有机会测试它,但它应该基于api文档工作。谢谢Khnanal,我用“item_to_text”函数更新了我的问题,%s是否意味着退出“?在我更新的问题中,在join语句中的何处/如何放置转义符?哦,假设它是一个字符串列表,您根本不需要在项目_to _文本上转义它。基本上%s会让mysql知道它需要一个字符串,然后它会转义它得到的字符串。非常感谢!很高兴它帮助了你!
def item_to_text(self, item):
return ', '.join(item.values()) # assuming item.values() returns a list or a tuple