Sql server pyodbc参数化sql结果计数不正确
我正在使用Sql server pyodbc参数化sql结果计数不正确,sql-server,parameters,pyodbc,Sql Server,Parameters,Pyodbc,我正在使用pyodbc在sqlserver表上运行一个不同的计数。当我以本机方式在SQLServer中运行查询时,会得到不同的结果 columns = ['A','B','C'] for col in columns: cursor.execute("select count(distinct(?)) from table",col) print (col) b = cursor.fetchone() distinctcount = b[0] prin
pyodbc
在sqlserver
表上运行一个不同的计数。当我以本机方式在SQLServer
中运行查询时,会得到不同的结果
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 count(*),则结果与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
参数替换不能用于指定列(或表)名称,只能指定列值。您执行的查询本质上是
从表中选择计数(不同('A'))
这就是返回1
,因为所有行的文本值'A'
都是相同的,所以只有一个不同的值
要指定列名,您需要使用动态SQL,例如
sql=“从表中选择计数(不同([{}])”。格式(列)
cursor.execute(sql)