为了账号安全,请及时绑定邮箱和手机立即绑定

MySQL语句python转义单引号'

MySQL语句python转义单引号'

翻过高山走不出你 2021-03-30 13:10:56
我在下面的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()        )
查看完整描述

1 回答

?
HUX布斯

TA贡献1876条经验 获得超6个赞

返回字符串模板的元组和变量的元组,游标可以执行(模板,(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 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


查看完整回答
反对 回复 2021-04-13
  • 1 回答
  • 0 关注
  • 424 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号