python-mysqlHow do I use a MySQL database with Python?
Using a MySQL database with Python involves using a library to make the connections. The most popular one is MySQL Connector/Python.
The following example code shows how to connect to a MySQL database and run a query:
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)
This code will output the contents of the customers table:
('John', 'Highway 21')
('Peter', 'Lowstreet 4')
('Amy', 'Apple st 652')
('Hannah', 'Mountain 21')
The code consists of the following parts:
import mysql.connector
- imports the MySQL Connector/Python library.mydb = mysql.connector.connect(...)
- connects to the MySQL database using the provided parameters.mycursor = mydb.cursor()
- creates a cursor object to execute queries.mycursor.execute("SELECT * FROM customers")
- executes the query to select all records from the customers table.myresult = mycursor.fetchall()
- fetches all the results from the query.for x in myresult: print(x)
- iterates through the results and prints them.
For more information, please refer to the MySQL Connector/Python documentation.
More of Python Mysql
- How can I connect Python to a MySQL database?
- How do I use Python to authenticate MySQL on Windows?
- How can I use Python to retrieve data from MySQL?
- How do I check the version of MySQL I am using with Python?
- How do I use Python to connect to a MySQL database using XAMPP?
- How do I show databases in MySQL using Python?
- How to compile a MySQL-Python application for x86_64-Linux-GNU-GCC?
- How do I use a cursor to interact with a MySQL database in Python?
- How do I execute a batch insert into a MySQL database using Python?
- How do I download MySQL-Python 1.2.5 zip file?
See more codes...