Python - SQL 语句中的特殊字符
Python - special characters in SQL statement
我正在使用 ODBC(Python ODBC 模块)连接到 MS Access。代码的一部分将一些值放入数据库中。看起来类似于:
for item in changes:
format_str = """INSERT INTO changes (short_description) VALUES ('{short_description}');"""
sql_command = format_str.format(short_description =item.short_description)
cursor.execute(sql_command)
cursor.commit()
问题是returns语法错误:
pypyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression
我发现这是因为我有一个案例 short_description 像这样:
The Service Request status is not changing to \"OPEN', once dispatched
to another group
问题出在 OPEN 之后的“'”。
在这里为您提供全貌。实际上我看到的字符串是这样的:
The Service Request status is not changing to "OPEN', once dispatched
to another group
我从提供数据的应用程序的 API 中获取带有“\”的字符串。它添加“\”来转义字符串,但不是所有地方。
问题是 - 最简单的解决方法是什么?
理论上我可以 replace\remove 不需要的标志,但万一我想保持原样呢?
对于任何其他情况,一切正常。
您应该使用 parameters 来避免 sql 注入:
for item in changes:
sql_command = """INSERT INTO changes (short_description) VALUES (?);"""
cursor.execute(sql_command, (item.short_description,) )
cursor.commit()
我正在使用 ODBC(Python ODBC 模块)连接到 MS Access。代码的一部分将一些值放入数据库中。看起来类似于:
for item in changes:
format_str = """INSERT INTO changes (short_description) VALUES ('{short_description}');"""
sql_command = format_str.format(short_description =item.short_description)
cursor.execute(sql_command)
cursor.commit()
问题是returns语法错误:
pypyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression
我发现这是因为我有一个案例 short_description 像这样:
The Service Request status is not changing to \"OPEN', once dispatched to another group
问题出在 OPEN 之后的“'”。
在这里为您提供全貌。实际上我看到的字符串是这样的:
The Service Request status is not changing to "OPEN', once dispatched to another group
我从提供数据的应用程序的 API 中获取带有“\”的字符串。它添加“\”来转义字符串,但不是所有地方。
问题是 - 最简单的解决方法是什么? 理论上我可以 replace\remove 不需要的标志,但万一我想保持原样呢?
对于任何其他情况,一切正常。
您应该使用 parameters 来避免 sql 注入:
for item in changes:
sql_command = """INSERT INTO changes (short_description) VALUES (?);"""
cursor.execute(sql_command, (item.short_description,) )
cursor.commit()