python-mysqlHow do I output data from MySQL to Python?
To output data from MySQL to Python, you can use the mysql.connector
library. This library allows you to connect to a MySQL database and execute SQL queries from within Python.
For example, to select and print all rows from a table named employees
:
import mysql.connector
# Connect to the database
db = mysql.connector.connect(
host="localhost",
user="user",
passwd="passwd",
database="mydatabase"
)
# Create a cursor (an object to iterate over the results)
cursor = db.cursor()
# Execute the query
cursor.execute("SELECT * FROM employees")
# Fetch and print the results
result = cursor.fetchall()
for x in result:
print(x)
Output example
(1, 'John', 'Doe', '[email protected]')
(2, 'Mary', 'Moe', '[email protected]')
(3, 'Julie', 'Dooley', '[email protected]')
The code above consists of the following parts:
- Importing the
mysql.connector
library - Connecting to the database
- Creating a cursor
- Executing the query
- Fetching and printing the results
For more information, see the MySQL Connector/Python Developer Guide.
More of Python Mysql
- How do I connect to XAMPP MySQL using Python?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How can I install the MySQL-Python (Python 2.x) module?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I connect Python to a MySQL database?
- How do I use Python to update multiple columns in a MySQL database?
- How do I use Python to query MySQL with multiple conditions?
- How do I use Python to authenticate MySQL on Windows?
- How do I use a Python MySQL refresh cursor?
- How do I use a cursor to interact with a MySQL database in Python?
See more codes...