【问题标题】:Python and MySQL query with quotes带引号的 Python 和 MySQL 查询
【发布时间】:2017-11-25 09:35:38
【问题描述】:

使用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)

产生同样的错误。

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

【问题讨论】:

标签: python mysql string python-3.x quotes


【解决方案1】:

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

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)

【讨论】:

    猜你喜欢
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    相关资源
    最近更新 更多