python-mysqlHow can I use Python to retrieve data from MySQL?
You can use Python to retrieve data from MySQL by using the Python MySQL connector library. This library provides an interface for connecting to a MySQL database server and executing SQL statements.
Example code
import mysql.connector
# Connect to the database
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="passwd",
database="mydatabase"
)
mycursor = mydb.cursor()
# Execute a query
mycursor.execute("SELECT * FROM customers")
# Fetch all the results
myresult = mycursor.fetchall()
# Print the results
for x in myresult:
print(x)
Output example
(1, 'John', 'Lowstreet 4')
(2, 'Peter', 'Lowstreet 5')
(3, 'Amy', 'Lowstreet 6')
The code consists of the following parts:
- Importing the MySQL Connector library -
import mysql.connector
- Connecting to the database -
mydb = mysql.connector.connect(host="localhost", user="user", passwd="passwd", database="mydatabase")
- Creating a cursor object -
mycursor = mydb.cursor()
- Executing a query -
mycursor.execute("SELECT * FROM customers")
- Fetching the results -
myresult = mycursor.fetchall()
- Printing the results -
for x in myresult: print(x)
Helpful links
More of Python Mysql
- How can I connect to MySQL using Python?
- How can I use Python to interact with a MySQL database using YAML?
- How do I use Python to connect to a MySQL database using XAMPP?
- How can I connect Python to a MySQL database?
- How can I use Python to update multiple rows in a MySQL database?
- How to compile a MySQL-Python application for x86_64-Linux-GNU-GCC?
- How do I use Python to authenticate MySQL on Windows?
- How do I check the version of MySQL I am using with Python?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How do I use a Python variable in a MySQL query?
See more codes...