我需要在 MySql 数据库中插入一个包含双引号的值:
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"]
的数据
我该如何摆脱它?
最佳答案
不要,不要,不要对 SQL 查询使用 .format
。使用内置的数据库转义机制:
sql_pattern = 'INSERT INTO Table(column1, column2, column3...) VALUES(%s, %s.....)'
...
cursor.execute(sql_pattern, (item["attr1"], item["attr2"]...,))
.execute
会将每个 %s 替换为值的适当(安全!)字符串表示形式,可以是字符串、整数、 float 等。% 周围没有额外的引号
,因为 sql_patter
中的 s.execute
将根据参数类型添加它们。
关于python - 将双引号插入 MySql 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16370197/