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
Line | Description |
---|---|
1-5 | Specify information about the database connection. |
10 | Defines a method named connectMySQLDB() . |
11 + 21 | The 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-17 | Connects 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-19 | If connection is established return MySQLConnection object. |
21-23 | If 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)