Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
seaborn.countplot() in Python
Next article icon

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 usegeeks(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 databaseimportmysql.connectormydb=mysql.connector.connect(host="localhost",user="root",password="root123",database="geeks")# Create a cursor objectmycursor=mydb.cursor()# Execute the queryquery="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 connectionmydb.close()

Output;

5

Example 2:

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

Python3
# Establish connection to MySQL databaseimportmysql.connectormydb=mysql.connector.connect(host="localhost",user="root",password="root123",database="geeks")# Create a cursor objectmycursor=mydb.cursor()# Execute the queryquery="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 connectionmydb.close()

Output:

2

Improve
Article Tags :
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp