python-mysqlHow can I get the number of rows returned when querying a MySQL database with Python?
To get the number of rows returned when querying a MySQL database with Python, you can use the cursor.rowcount
attribute of the cursor
object. This attribute returns the number of rows that were affected by the last SELECT
statement.
For example:
import mysql.connector
# Connect to the database
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="passwd",
database="mydatabase"
)
# Create a cursor object
my_cursor = mydb.cursor()
# Execute a query
my_cursor.execute("SELECT * FROM customers")
# Get the number of rows
num_rows = my_cursor.rowcount
print(num_rows)
Output example
4
Code explanation
- Importing the
mysql.connector
library -import mysql.connector
- Connecting to the database -
mydb = mysql.connector.connect(host="localhost", user="user", passwd="passwd", database="mydatabase")
- Creating a cursor object -
my_cursor = mydb.cursor()
- Executing a query -
my_cursor.execute("SELECT * FROM customers")
- Getting the number of rows -
num_rows = my_cursor.rowcount
- Printing the number of rows -
print(num_rows)
Helpful links
More of Python Mysql
- How can I use Python to retrieve data from MySQL?
- How do I use an online compiler to write Python code for a MySQL database?
- How can I use the MySQL Connector in Python?
- How can I connect to MySQL using Python?
- How do I access MySQL using Python?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I retrieve the last insert ID in MySQL using Python?
- How do I update values in a MySQL database using Python?
- How can I connect Python and MySQL?
- How can I connect Python to a MySQL database?
See more codes...