pyodbc 参数化 sql 结果计数不同不正确

pyodbc parameterised sql result count distinct incorrect

我正在 运行使用 pyodbcsql server table 进行不同计数。当我 运行 本机 sql server 中的查询时,我得到了不同的结果。

columns = ['A','B','C']

for col in columns: 
    cursor.execute("select count(distinct(?)) from table",col)
    print (col)
    b = cursor.fetchone()
    distinctcount = b[0]
    print ('distinctcount %s '% distinctcount)

当所有列的实际值应为 151988 时,输出将所有列显示为“1”。

A
distinctcount 1 
B
distinctcount 1 

如果我运行一个简单的select计数(*),那么结果和sql server中的结果是一致的。

for col in columns: 
    cursor.execute("select count(?) from table" , col)
    print (col)
    a = cursor.fetchone()
    rowcount = a[0]
    print ('rowcount %s '% rowcount)

结果:

A
rowcount 151988 
B
rowcount 151988 

参数替换不能用于指定列(或 table)names,只能指定列 values。您正在执行的查询本质上是

select count(distinct('A')) from table

返回 1 因为文字值 'A' 对于所有行都是相同的,所以只有一个不同的值。

要指定列 name,您需要使用动态 SQL,例如,

sql = "select count(distinct([{}])) from table".format(col)
cursor.execute(sql)