简体   繁体   中英

Count of records of table in mssql server

I am trying to fetch the no. of records/count from a mssql table but getting:

pymssql.ColumnsWithoutNamesError: Specified as_dict=True and there are columns with no names: [0]

Here is what I am trying:

cur = hook.get_cursor()                        
cur.execute(self.sql)

And the query is:

select count(*) from abc

See here :

The problem is that if you open the connection or cursor with as_dict=True, then every column in the output has to have a name. With a regular database table column, the output name inherits from the column name. If you have a SQL expression like calling a function on a column name (eg: MAX(foo)), then the output column doesn't have a name and so it doesn't get displayed. There are two things you can do to make it work:

 1. Give the SQL expression a name -- eg: SELECT MAX(foo) AS [MAX(foo)]... 2. Don't use as_dict=True for these queries 

I think same for COUNT function. So try to give the result a name with "AS".

Or have a look for the _mssql module of pymsql (here is also an example for COUNT:

import _mssql
conn = _mssql.connect(server='SQL01', user='user', password='password', database='mydatabase')
numemployees = conn.execute_scalar("SELECT COUNT(*) FROM employees")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM