How to connect to a MySQL database in Python

To connect with a MySQL database, you have to install a specific module with pip:

pip install mysql-connector-python

Then you import mysql.connector and to create a connection you call mysql.connector.connect(), passing the host, user, and password.

In this example we are connecting to a MySQL instance with host named "test_host", a user called "test_user", and a password "test_password".

After that we create a cursor, which is the object we are going to call the execute the commands in the database.

We are making a simple query from a table called "employees" and this query is executed by calling cursor.execute(sql).

Then we use cursor.fetchall() to bring the results and print each record with a for loop.

Finally, we close the connection at the end to release resources as a good practice.

import mysql.connector

host_name = "test_host"
user_name = "test_user"
user_password = "test_password"

connection = mysql.connector.connect(
    host=host_name,
    user=user_name,
    passwd=user_password
)

cursor = connection.cursor()

sql = "SELECT * FROM employees"

cursor.execute(sql)

records = cursor.fetchall()

for record in records:
    print(record)

connection.commit()

connection.close()