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 do I use Python to show the MySQL processlist?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I connect Python to a MySQL database?
- How can I use Python and MySQL to create a login system?
- How can I use Python to interact with a MySQL database using YAML?
- How can I use Python to yield results from a MySQL database?
- How can I print the result of a MySQL query in Python?
- How can I use Python to retrieve data from MySQL?
- How can I connect to MySQL using Python?
See more codes...