MySQL Database Connections

In this lesson, you will learn how to connect the MySQL database in Python using the MySQL Connector module.
To connect to a mysql database, instead of using the pyodbc.connect() method, use the mysql.connector.connect() method.

First import the MySQL Connector module:

import mysql.connector

Code Explanation

LineDescription
1-5Specify information about the database connection.
10Defines a method named connectMySQLDB().
11 + 21The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.
12-17Connects to a mysql database via the connect() method of the mysql connector. In its simpliest form, connect() will open a connection to a MySQL server and return a MySQLConnection object.
19-19If connection is established return MySQLConnection object.
21-23If an error occurs in the try block, it is intercepted and an error message is output via the error object e.
server = 'server_name'
database = 'db_name'
username = 'user_name'
password = 'user_pw'
driver = '{ODBC Driver 17 for SQL Server}'

# --------------------------------------------------
# MySQL Database Connection
# --------------------------------------------------
def connectMySQLDB():
    try:
        connection = mysql.connector.connect(
            host=server,
            database=database,
            user=username,
            password=password
        )
        if connection.is_connected():
            return connection

    except Error as e:
        print("Error while connecting to MySQL Database: ", e)
        sys.exit(1)