How to connect to MySQL in Python

Connecting to MySQL from Python offers many solutions, but I like the official MySQL connector. You can install the module using pip.

sudo pip install mysql-connector-python

Once the module is installed you can connect to MySQL using the following code.

import mysql.connector
 
cnx = mysql.connector.connect(user='mysql_username',
                              password='mysql_password',
                              host='localhost',
                              database='database_name')
cursor = cnx.cursor()
 
# Example query to connect to the MySQL database and user table and user column.
query = "SELECT user FROM user"
cursor.execute(query)
 
# Iterate over the resulting cursor and print
for user in cursor:
    print(user)
 
cursor.close()
cnx.close()

More detailed information can be found here.

Leave a Reply

Your email address will not be published. Required fields are marked *