python-mysqlHow can I get the row count of a MySQL table using Python?
You can get the row count of a MySQL table using Python by executing a SQL query with the COUNT() function.
Example code
#import mysql.connector
import mysql.connector
#connect to database
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
#create cursor
mycursor = mydb.cursor()
#create sql query
sql = "SELECT COUNT(*) FROM customers"
#execute sql query
mycursor.execute(sql)
#fetch result
myresult = mycursor.fetchone()
#print result
print(myresult)
Output example
(50,)
Code explanation
import mysql.connector- imports the mysql.connector module.mydb = mysql.connector.connect()- connects to the database.mycursor = mydb.cursor()- creates a cursor to the database.sql = "SELECT COUNT(*) FROM customers"- creates a SQL query with theCOUNT()function.mycursor.execute(sql)- executes the SQL query.myresult = mycursor.fetchone()- fetches the result of the query.print(myresult)- prints the result.
Helpful links
More of Python Mysql
- How do I access MySQL using Python?
- How can I convert a MySQL query to JSON using Python?
- How do I perform a MySQL health check using Python?
- How can I use Python and MySQL together to perform asynchronous operations?
- How can I use Python to retrieve data from MySQL?
- How can I connect Python to a MySQL database?
- How do I set up a secure SSL connection between Python and MySQL?
- How do I download MySQL-Python 1.2.5 zip file?
- How do I install a Python package from PyPI into a MySQL database?
- How can I use Python and MySQL to generate a PDF?
See more codes...