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.connectorlibrary - 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 can I access MySQL using Python?
- How can I connect to MySQL using Python?
- 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 do I access MySQL using Python?
- How do I connect Python with MySQL using XAMPP?
- How do I use Python to authenticate MySQL on Windows?
- How can I create a web application using Python and MySQL?
- How can I use Python Kivy with MySQL?
See more codes...