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 can I access MySQL using Python?
- How can I convert all "None" values to "null" in a Python-MySQL database?
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How can I connect to MySQL using Python?
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python to a MySQL database?
- How do I use Python to query MySQL with multiple conditions?
- How do I use Python to connect to a MySQL database using XAMPP?
- How can I create a web application using Python and MySQL?
- How do Python and MySQL compare to MariaDB?
See more codes...