首页 > 解决方案 > SQL pyodbc 问题

问题描述

我尝试将以下查询作为准备好的语句执行:

self.cursor.execute("select distinct ? from isap.tn_documentation where ? = '?' and  ? <> ''", attribute2, attribute1, i.text(0), attribute2)

执行后我得到以下错误:

SQL 包含 3 个参数标记,但提供了 4 个参数', 'HY000

标签: pythonsqlpyodbc

解决方案


您不能将列名作为查询参数传递。您需要连接查询字符串中的列名(同时将列值保留为参数)。

这应该看起来像:

self.cursor.execute(
    "select distinct " 
        + attribute2 
        + " from isap.tn_documentation where " 
        + attribute1 + " = ? and " + attribute2 + " <> ''", 
    i.text(0)
)

请注意,这样做会将您的代码暴露给 SQL 注入:如果您的属性输入来自您的代码之外,这是一个严重的安全漏洞。您需要确保它们不包含恶意数据(例如,通过根据允许值的固定列表检查每个属性的值:这应该很容易,因为我们正在处理列名)。


推荐阅读