繁体   English   中英

我如何计算表中的列数

[英]how can i count number of columns in table

我尝试通过python计算表(访问数据库)中的列数,但是我遇到了先前的错误 在此处输入图片说明

#connector is the module file for connect to database 

import os
import pyodbc
class Connect():
# connect to database
    dataFile = "youssri_knowledge_v1.accdb"
    databaseFile  = os.getcwd() + "\\" + dataFile
    connectionString = "Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=%s" % databaseFile
    dbConnection   = pyodbc.connect(connectionString)
    cursor = dbConnection.cursor()
    cursor.execute("select * from tinformation")
    rows = cursor.fetchall()

# fro test the connection
    #for row in rows:
        #print (row)
# select number of columns
    tinfo_col_number= cursor.execute ("select (*) from tinofrmation")
    print (tinfo_col_number)

也许这不是最优雅的解决方案,但是如果您需要知道行数/列数和内容,则不需要两次查询数据库; 当你做

rows = cursor.fetchall()

您已经有了一个列表列表,其中每个子列表都是数据库的一行,因此,如果您想要行号,可以执行以下操作:

len(rows)

如果您想要列号,则只需选择一行并计算有多少个元素即可。...即使某行没有所有元素,也将使用空值报告,因此:

len(rows[0])

可能您可以更改查询,MSSQL的语法与MySQL略有不同。 尝试这个:

 tinfo_col_number= cursor.execute ("SELECT Count(*) FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'tinofrmation'")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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