SQL pyodbc 问题
SQL pyodbc issue
我尝试将以下查询作为准备语句执行:
self.cursor.execute("select distinct ? from isap.tn_documentation where ? = '?' and ? <> ''", attribute2, attribute1, i.text(0), attribute2)
执行后出现以下错误:
The SQL contains 3 parameter markers, but 4 parameters were supplied', 'HY000
您不能将列名作为查询参数传递。您需要连接查询字符串中的列名(同时将列值保留为参数)。
这应该是这样的:
self.cursor.execute(
"select distinct "
+ attribute2
+ " from isap.tn_documentation where "
+ attribute1 + " = ? and " + attribute2 + " <> ''",
i.text(0)
)
请注意,这样做会使您的代码暴露于 SQL 注入:如果您的属性输入来自代码外部,这是严重的安全漏洞。您需要确保它们不包含恶意数据(例如,根据固定的允许值列表检查每个属性的值:这应该很容易,因为我们正在处理列名)。
我尝试将以下查询作为准备语句执行:
self.cursor.execute("select distinct ? from isap.tn_documentation where ? = '?' and ? <> ''", attribute2, attribute1, i.text(0), attribute2)
执行后出现以下错误:
The SQL contains 3 parameter markers, but 4 parameters were supplied', 'HY000
您不能将列名作为查询参数传递。您需要连接查询字符串中的列名(同时将列值保留为参数)。
这应该是这样的:
self.cursor.execute(
"select distinct "
+ attribute2
+ " from isap.tn_documentation where "
+ attribute1 + " = ? and " + attribute2 + " <> ''",
i.text(0)
)
请注意,这样做会使您的代码暴露于 SQL 注入:如果您的属性输入来自代码外部,这是严重的安全漏洞。您需要确保它们不包含恶意数据(例如,根据固定的允许值列表检查每个属性的值:这应该很容易,因为我们正在处理列名)。