【问题标题】:MySQL statement python escape single quote 'MySQL 语句 python 转义单引号 '
【发布时间】:2018-12-01 10:17:04
【问题描述】:

我有下面的 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, 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()
        )

【问题讨论】:

    标签: python mysql scrapy character mysql-error-1064


    【解决方案1】:

    返回一个字符串模板元组和变量元组,游标可以执行(template, (v1,v2,..))

    cursor.execute(‘insert into tablename (c, d) values (%s, %s)’, (v1, v2))
    

    基于API Docs

    编辑 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: 我很确定,如果您真的想将语句作为单个字符串传递,则必须在字符串本身中有一个 \ ,因此使用 INT\\'L

    编辑 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 语句中放置转义符?
    • 哦,你根本不需要在 item_to_text 上转义它,假设它是一个字符串列表。基本上 %s 会让 mysql 知道它需要一个字符串,然后它将转义它进入的字符串。
    • 非常感谢卡纳尔!
    • 很高兴它帮助了你!
    猜你喜欢
    • 2012-10-05
    • 1970-01-01
    • 2011-06-13
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多