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 can I use Python to retrieve data from MySQL?
- How can I connect Python to a MySQL database?
- How can I use Yum to install the MySQLdb Python module?
- How do I connect Python with MySQL using XAMPP?
- How do I connect to a MySQL database using XAMPP and Python?
- How do I download MySQL-Python 1.2.5 zip file?
- How do I use Python to authenticate MySQL on Windows?
- How can I use Python to make a MySQL request?
- How do I decide between using Python MySQL and PyMySQL?
- How do I use Python to show the MySQL processlist?
See more codes...