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.connectorlibrary. - 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 can I connect Python and MySQL?
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python to a MySQL database?
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How can I use Python to interact with a MySQL database using YAML?
- How can I connect Python to a MySQL database using an Xserver?
- How do I connect Python with MySQL using XAMPP?
- How do I use Python to query MySQL with multiple conditions?
- How do Python and MySQL compare to MariaDB?
- How can I set a timeout for a MySQL connection in Python?
See more codes...