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 update multiple columns in a MySQL database?
- How can I connect Python to a MySQL database using an Xserver?
- How can I connect Python and MySQL?
- How do I set up a secure SSL connection between Python and MySQL?
- How can I use Python and MySQL to generate a PDF?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How do I use Python to authenticate MySQL on Windows?
- How can I export data from a MySQL database to a CSV file using Python?
- How do I use Python to show the MySQL processlist?
- How do I use a SELECT statement in Python to query a MySQL database?
See more codes...