python-mysqlHow can I use Python to retrieve data from a MySQL database?
To use Python to retrieve data from a MySQL database, you can use the MySQL Connector/Python
library. Below is an example code block to connect to a MySQL database and retrieve the data:
import mysql.connector
# Connect to the database
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="password"
)
# Create a cursor
mycursor = mydb.cursor()
# Execute a query
mycursor.execute("SELECT * FROM customers")
# Retrieve the results
myresult = mycursor.fetchall()
# Print the results
for x in myresult:
print(x)
The code above consists of the following parts:
- Import the
mysql.connector
library - Connect to the database
- Create a cursor
- Execute a query
- Retrieve the results
- Print the results
Helpful links
More of Python Mysql
- How do I connect Python with MySQL using XAMPP?
- How can I use Python to retrieve data from MySQL?
- How can I use Yum to install the MySQLdb Python module?
- How can I use Python to insert a timestamp into a MySQL database?
- How can I connect to a MySQL database using Python and SSH?
- How can I connect to MySQL using Python?
- How can I get the column names from a MySQL database using Python?
- How do I download MySQL-Python 1.2.5 zip file?
- How do I use Python to query MySQL with multiple conditions?
- How do I access MySQL using Python?
See more codes...