【发布时间】: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)
产生同样的错误。
如何解决这个问题?也许,一旦函数返回了字符串,是否可以用三引号重新定义它们?
【问题讨论】:
-
将值作为参数传递给
cursor.execute,而不是将它们格式化为您的字符串。 -
@khelwood 我再次尝试编辑了这个问题,如果它是你所说的。如果不是,可以举个简单的例子吗?
标签: python mysql string python-3.x quotes