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 access MySQL using Python?
- How can I connect Python to a MySQL database?
- 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 interact with a MySQL database using YAML?
- How do I install a Python package from PyPI into a MySQL database?
- How can I convert data from a MySQL database to XML using Python?
- How do I use Python to handle MySQL NULL values?
- How do I use the "on duplicate key update" statement in Python and MySQL?
- How can I use Python to yield results from a MySQL database?
See more codes...