遍历数据库中表的列并打印其中的记录数

已经连接到数据库,需要遍历表的列并打印每个档案中的记录数,因为名称打印如下

import mysql.connector
from mysql.connector import Error
try:
   mySQLconnection = mysql.connector.connect(host='localhost',
                                    database='nmoorg',
                                   user='root',
                                   password='ChvU5M12')
   sql_select_Query = "select * from archive"
   cursor = mySQLconnection .cursor()
   cursor.execute(sql_select_Query)
   records = cursor.fetchall()
   print("Total number of rows in python_developers is - ",  cursor.rowcount)
   print ("Printing each row's column values i.e.  developer record")

   for row in records:
       print("archive name = ", row[1], )

   cursor.close()

except Error as e :
    print ("Error while connecting to MySQL", e )
finally:
    #closing database connection.
    if(mySQLconnection .is_connected()):
        connection.close()
        print("MySQL connection is closed")


我需要计算列而不是表中的记录数

最佳答案

SELECT COUNT(*) num FROM archive


是对表中的行进行计数的方法。

SELECT COUNT(*) num, COUNT(column) num_column FROM archive


是对所有行和archive.column中具有非空值的行数进行计数的方法。

我想这就是通过计算列而不是表中的记录数来表示的意思。

通过执行SELECT *并对结果集中的行进行计数的效率非常低。另外,如果表有任何有趣的大小,.fetchall()将耗尽您的RAM。 SQL的全部目的是允许您处理比RAM大几个数量级的数据集。

关于python - 遍历数据库中表的列并打印其中的记录数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56527695/

10-14 14:06
查看更多