
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to count SQL table columns using Python?
It may be required to count the number of columns present in a SQL table.
This is done using count(*) function with information_schema.columns and the WHERE clause. The WHERE clause is used to specify the name of the table whose columns are to be counted.
Syntax
SELECT COUNT(*) FROM information_schema.columns WHERE table_name= ‘your_table_name’
Steps to count columns in a table using MySQL in python
import MySQL connector
establish connection with the connector using connect()
create the cursor object using cursor() method
create a query using the appropriate mysql statements
execute the SQL query using execute() method
close the connection
Suppose we have a table named “Students” as below −
+----------+---------+-----------+------------+ | Name | Class | City | Marks | +----------+---------+-----------+------------+ | Karan | 4 | Amritsar | 95 | | Sahil | 6 | Amritsar | 93 | | Kriti | 3 | Batala | 88 | | Khushi | 9 | Delhi | 90 | | Kirat | 5 | Delhi | 85 | +----------+---------+-----------+------------+
Example
We want to count the number of columns in the above table.
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()
The above returns the number of columns present in the table named “Students”.
Output
4
- Related Articles
- How to perform arithmetic across columns of a MySQL table using Python?
- How to count number of columns in a table with jQuery
- SQL using Python
- SQL Query to Convert Rows to Columns in SQL Server
- How to retrieve particular columns of a table using JDBC program?
- SQL using Python and SQLite
- How to sql insert items from a list or collection in to table using JDBC?
- How to get the number of columns of a table using JDBC?
- How to merge table columns in HTML?
- Count the number of columns in a MySQL table with Java
- Write a SQL query to count the number of duplicate TRANSACTION_ID in an ORDERS DB2 table
- How to insert data into a table with auto-incremented columns using JDBC?
- How to Display the multiplication Table using Python?
- How to run .SQL script using JDBC?
- How to create table rows & columns in HTML?

Advertisements