python-mysqlHow can I read data from a MySQL database using Python?
To read data from a MySQL database using Python, you need to use a library called MySQL Connector/Python. This library is used to connect to MySQL databases and execute queries.
The following example code shows how to connect to a MySQL database and execute a query to retrieve all the rows from the users
table:
import mysql.connector
# Connect to the database
db = mysql.connector.connect(
host="localhost",
user="root",
passwd="password",
database="mydatabase"
)
# Create a cursor object
cursor = db.cursor()
# Execute a query
cursor.execute("SELECT * FROM users")
# Fetch all the rows
results = cursor.fetchall()
# Print the results
print(results)
The code above consists of the following parts:
- Import the
mysql.connector
library. - Connect to the MySQL database using the
connect()
method. - Create a cursor object using the
cursor()
method. - Execute a query using the
execute()
method. - Fetch the results using the
fetchall()
method. - Print the results.
For more information, see the MySQL Connector/Python documentation.
More of Python Mysql
- How do I access MySQL using Python?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How do I use a Python MySQL refresh cursor?
- How can I use Python to retrieve data from MySQL?
- How do I check the version of MySQL I am using with Python?
- How can I resolve the "no database selected" error when using Python and MySQL?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I connect to MySQL using Python?
- How can I connect Python to a MySQL database?
- How do I use a SELECT statement in Python to query a MySQL database?
See more codes...