Python 和 MySQL 带引号的查询

Python and MySQL query with quotes

使用 Python3 中的脚本,从文件中提取一些字符串后,它们应该用作要插入到 MySQL 数据库中的数据,如下所示:

query1 = """INSERT INTO {:s} VALUES ({:s}, {:s}, {:s}, {:s});""".format(table1,"""0""",string1,string2,string3)
cursor1.execute(query1)

一些字符串包含不同且令人不快的引号,例如:

a "'double quoted'" example string

如果我用三引号定界符定义一些示例字符串

string1 = """a "'double quoted'" example string"""

以上查询成功。相反,如果字符串在解析外部文件后由函数返回,则查询会生成错误:

_mysql_exceptions.ProgrammingError: (1064, '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 \'first string, "\'Quoted part\'" of second string, , Third string\' at line 1')

我也试过:

query1 = """INSERT INTO {:s} VALUES ('{:s}', '{:s}', '{:s}', '{:s}');""".format(table1,"""0""",string1,string2,string3)

但产生了同样的错误。

还有

query1 = """INSERT INTO %s VALUES (%s, %s, %s, %s);"""
data1 = ("""table1"""","""0""",string1,string2,string3)
cursor1.execute(query1,data1)

query1 = """INSERT INTO %s VALUES ('%s', '%s', '%s', '%s');"""
data1 = ("""table1"""","""0""",string1,string2,string3)
cursor1.execute(query1,data1)

生成相同的错误。

如何解决这个问题?也许,一旦函数返回了字符串,是否可以用三引号重新定义它们?

这是向语句添加参数的方式。

sql = "INSERT INTO my_table VALUES (%s, %s, %s);"

cursor.execute(sql, [string1, string2, string3])

MySQLCursor.execute()

在此示例中,您不必明确引用这些值,因为您没有将它们粘贴到您的 SQL 中。此外,这更安全,因为如果字符串包含结束引号并且它们是恶意的 SQL,它将不会被执行。

您不能将 table 名称添加为参数,因此如果它在变量中,您 必须将其粘贴到您的 SQL:

sql = "INSERT INTO {} VALUES (%s, %s, %s);".format(table_name)