python-mysqlHow can I use Python to interact with a MySQL database?
Python can be used to interact with a MySQL database using the MySQL Connector/Python. This library provides an interface for connecting to a MySQL server and executing SQL statements.
Example code
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="passwd",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Output example
('John', 'Highway 21')
('Peter', 'Lowstreet 4')
('Amy', 'Apple st 652')
('Hannah', 'Mountain 21')
The code above:
- Imports the
mysql.connector
library (1) - Connects to a MySQL database (2)
- Creates a cursor object (3)
- Executes an SQL statement to select all records from the
customers
table (4) - Fetches all the results of the query (5)
- Prints out each row of the result (6)
Helpful links
More of Python Mysql
- How do I use Python to update multiple columns in a MySQL database?
- How do I connect to a MySQL database using XAMPP and Python?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How can I connect Python to a MySQL database?
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How can I access MySQL using Python?
- How can I use a MySQL variable in Python?
- How do I use Python to show the MySQL processlist?
- How do I use a SELECT statement in Python to query a MySQL database?
- How do I use a Python MySQL refresh cursor?
See more codes...