Skip to content
Related Articles

Related Articles

Count SQL Table Column Using Python

View Discussion
Improve Article
Save Article
  • Last Updated : 23 Dec, 2020

Prerequisite: Python: MySQL Create Table

In this article, we are going to see how to count the table column of a MySQL Table Using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicating with a MySQL database. 

We are going to use geeks(Database name) database and table describing the salary.

Approach:

  • Import module.
  • Make a connection request with the database.
  • Create an object for the database cursor.
  • Execute the following MySQL query:

SELECT count(*) AS New_column_name FROM information_schema.columns where table_name = ‘Table_name’;

Example 1:

In this example we are using this database with the following query;

Python3




# Establish connection to MySQL database
import mysql.connector
  
mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    password="root123",
    database="geeks"
)
  
# Create a cursor object
mycursor = mydb.cursor()
  
# Execute the query
query = "SELECT count(*) AS New_column_name FROM information_schema.columns where table_name = 'Persons';"
mycursor.execute(query)
  
myresult = mycursor.fetchall()
  
print(myresult[-1][-1])
  
# Close database connection
mydb.close()

Output;

5

Example 2:

In this example we are using this database with the following query;

Python3




# Establish connection to MySQL database
import mysql.connector
  
mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    password="root123",
    database="geeks"
)
  
# Create a cursor object
mycursor = mydb.cursor()
  
# Execute the query
query = "SELECT count(*) AS New_column_name FROM information_schema.columns where table_name = 'Salary';"
mycursor.execute(query)
  
myresult = mycursor.fetchall()
  
print(myresult[-1][-1])
  
# Close database connection
mydb.close()

Output:

2

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!