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 use Python to query MySQL with multiple conditions?
- How do I use Python to authenticate MySQL on Windows?
- How do I use Python to update multiple columns in a MySQL database?
- How do I use Python to show the MySQL processlist?
- How can I connect Python to a MySQL database?
- How can I use Python to interact with a MySQL database using YAML?
- How do Python and MySQL compare to MariaDB?
- How can I convert a MySQL query result to a Python dictionary?
- How do I connect to a MySQL database using XAMPP and Python?
- How can I use Python to perform an upsert on a MySQL database?
See more codes...