python-mysqlHow do I use Python to select data from a MySQL database?
To use Python to select data from a MySQL database, you can use the mysql.connector
module. This module provides an API for connecting to and interacting with a MySQL database.
Example code
import mysql.connector
# Connect to the database
db = mysql.connector.connect(
host="localhost",
user="user",
passwd="password",
database="mydatabase"
)
# Create a cursor object
cursor = db.cursor()
# Execute a query
cursor.execute("SELECT * FROM users")
# Fetch the results
result = cursor.fetchall()
# Print the results
print(result)
Output example
[(1, 'John', 'Doe', '[email protected]'), (2, 'Jane', 'Doe', '[email protected]')]
The code above can be broken down into the following parts:
- Import the
mysql.connector
module. - Connect to the database using
mysql.connector.connect()
and passing in the relevant connection details. - Create a cursor object using
db.cursor()
. - Execute a query using
cursor.execute()
. - Fetch the results using
cursor.fetchall()
. - Print the results.
Helpful links
More of Python Mysql
- How can I use Python to interact with a MySQL database using YAML?
- How do I use Python to authenticate MySQL on Windows?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How can I connect Python to a MySQL database?
- How can I use Python to make a MySQL request?
- How do I use Python to query MySQL with multiple conditions?
- How can I use the "order by" statement in Python to sort data in a MySQL database?
- How do Python and MySQL compare to MariaDB?
- How do I install a Python package from PyPI into a MySQL database?
- How to compile a MySQL-Python application for x86_64-Linux-GNU-GCC?
See more codes...