可能需要计算 SQL 表中存在的列数。
这是使用 count(*) 函数与 information_schema.columns 和 WHERE 子句完成的。WHERE 子句用于指定要对其列进行计数的表的名称。
SELECT COUNT(*) FROM information_schema.columns WHERE table_name= ‘your_table_name’
导入 MySQL 连接器
使用连接器建立连接 connect()
使用cursor()方法创建游标对象
使用适当的 mysql 语句创建查询
使用execute()方法执行 SQL 查询
关闭连接
假设我们有一个名为“Students”的表,如下所示 -
+----------+---------+-----------+------------+ | Name | Class | City | Marks | +----------+---------+-----------+------------+ | Karan | 4 | Amritsar | 95 | | Sahil | 6 | Amritsar | 93 | | Kriti | 3 | Batala | 88 | | Khushi | 9 | Delhi | 90 | | Kirat | 5 | Delhi | 85 | +----------+---------+-----------+------------+
我们要计算上表中的列数。
import mysql.connector db=mysql.connector.connect(host="your host", user="your username", password="your password",database="database_name") cursor=db.cursor() query="SELECT COUNT(*) FROM information_schema.columns WHERE table_name= "Students" " cursor.execute(query) col=cursor.fetchall() for x in col: print(x) db.close()
以上返回名为“Students”的表中存在的列数。
输出结果
4