带引号的 Python 和 MySQL 查询

标签 python mysql string python-3.x 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,它不会被执行。

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

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

关于带引号的 Python 和 MySQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44693751/

相关文章:

python - 有什么简单的方法可以使 python raw_input UI 更像 bash UI 吗?

javascript - 状态下拉列表将不会验证(php)

mysql - Mysql中如何通过另一行的另一列更新一行的一列的内容

c++ - 关于在 C++ 中通过 ASCII 将文本转换为十六进制

python - 简单的 Tic-Tac_Toe 游戏 Pygame

python - Python中基于印象的N-gram分析

python - 如何理解scikit-learn逻辑回归代码中的损失函数?

java - 如何解决自定义存储库 JPA 中的错误 "error in your SQL syntax"

Javascript 查找字符串是否以正斜杠结尾

c# - 如何安全地将字节数组转换为字符串并返回?