0

我需要在 MySql db 中插入一个包含双引号的值:

import MySQLdb
cursor = db.cursor()
sql_pattern = 'INSERT INTO Table(column1, column2, column3....) VALUES("{0}".....)'
data_object_array = get_data_object_array()
for item in data_object_array():
  sql = sql_pattern.format(item["attr1"], item["attr2"]....)
  cursor.execute(sql)

我有一个错误

_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 \'data" fdsfds5454 "data2"")\' at line 1')

"data" fdsfds5454 "data2"包含的数据在哪里item["attr1"]

我该如何摆脱它?

4

1 回答 1

4

不要,不要,不要用于.formatSQL 查询。使用内置的数据库转义机制:

sql_pattern = 'INSERT INTO Table(column1, column2, column3...) VALUES(%s, %s.....)'

...
  cursor.execute(sql_pattern, (item["attr1"], item["attr2"]...,))

.exectue%s将用正确的(安全!)值的字符串表示形式替换每个 %s,无论是字符串、整数、浮点数等。不是在in周围没有额外的引号sql_patter,因为.execute将根据参数类型添加它们。

于 2013-05-04T03:38:17.637 回答