MySQL语句python转义单引号'

我在下面的MySQL语句中使用python,但其中一个值中有一个单引号',因此出现以下错误:


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()

        )


翻过高山走不出你
浏览 425回答 1
1回答

HUX布斯

返回字符串模板的元组和变量的元组,游标可以执行(模板,(v1,v2,..))cursor.execute(‘insert into tablename (c, d) values (%s, %s)’, (v1, v2))基于API文档编辑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 socursor.execute(query(item))编辑3:我可以肯定,如果您真的想将语句作为单个字符串传递,则必须在字符串本身中包含一个\,从而使用INT \\'L编辑4:def item_to_text(self, item):    return ', '.join(item.values()) # assuming item.values() returns a list or a tuple
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python