Python - MySQL - Getting Started

Python

Share
python logo

In this tutorial we will learn to connect to MySQL database using Python.

Prerequisite

It is assumed that you have MySQL database server installed on your computer or server where you are executing your Python code.

Points to note!

For MySQL database you can checkout https://www.mysql.com.

If you want to learn MySQL then check out this MySQL tutorial.

Install MySQL Connector for Python

To work with MySQL database we have to first install the mysql-connector package.

We will be installing the mysql-connector using PIP package manager.

Run the following command in the terminal to install the package.

$ pip install mysql-connector

You can also checkout mysql-connector-python package to connect to MySQL database using Python.

Import mysql.connector

After installing mysql-connector package go ahead and import it by writing the following code.

import mysql.connector

Connect to database

Write the following Python code to connect to the MySQL database.

cnx = mysql.connector.connect(
  user='USERNAME',
  password='PASSWORD',
  host='127.0.0.1',
  database='DATABASE'
)

Where, USERNAME is the username for your database. PASSWORD is the password for the USERNAME. DATABASE is the name of the database that you want to connect to. The host is set to 127.0.0.1 which means localhost.

In the following example I am connecting to mydb database that I have on my system. The username for my system is root and the password is root1234.

cnx = mysql.connector.connect(
  user='root',
  password='root1234',
  host='127.0.0.1',
  database='mydb'
)

Handling database error

While trying to make database connection we may encounter errors. So, to handle errors we can take help of the try-except block.

In the following Python program we are connecting to the database and using the try-except block to handle any error.

# import module
import mysql.connector

# import errorcode
from mysql.connector import errorcode

try:
  cnx = mysql.connector.connect(
      user='root',
      password='root1234',
      host='127.0.0.1',
      database='mydb'
  )
except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print('Invalid credential. Unable to access database.')
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print('Database does not exists')
    else:
        print('Failed to connect to database')

print('Successfully connected to the database.')

# close connection
cnx.close()

On success the above code will print the following output.

Successfully connected to the database.

Close database connection

It is a good practice to close the database connection after we are done with our database task.

To close the connection we use the close() method.

In the following Python program we are closing the database connection that we established earlier.

cnx.close()
Share