gpt4 book ai didi

python - MySQL语句python转义单引号'

转载 作者:行者123 更新时间:2023-11-29 05:54:29 31 4
gpt4 key购买 nike

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

最佳答案

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

关于python - MySQL语句python转义单引号',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50979415/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com