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 do I use Python to query MySQL with multiple conditions?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How can I use Python and MySQL to generate a PDF?
- How do I connect Python with MySQL using XAMPP?
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How can I connect Python to a MySQL database?
- How can I install the MySQL-Python (Python 2.x) module?
- How do I use Python to authenticate MySQL on Windows?
- How do I connect to a MySQL database using Python and MySQL Workbench?
- How do I use a Python variable in a MySQL query?
See more codes...