Getting Started

Python - IntroductionPython - Hello World ProgramPython - SyntaxPython - Data TypesPython - Variables

Operators

Python - Arithmetic OperatorsPython - Relational OperatorsPython - Logical OperatorsPython - Assignment OperatorsPython - Bitwise OperatorsPython - Membership OperatorsPython - Identity OperatorsPython - Increment and Decrement Operators

Conditions

Python - If Else statement

Loop

Python - While LoopPython - For Loop

Numbers

Python - NumbersPython - Number Conversion

Strings

Python - StringsPython - String OperatorsPython - String FormattingPython - String MethodsPython - String Format Method

List

Python - ListPython - List Methods

Tuple

Python - Tuple

Set

Python - SetPython - Set Methods

Dictionary

Python - DictionaryPython - Dictionary Methods

Functions

Python - FunctionsPython - Functions - Variable length argumentsPython - Lambda Function

Scope of Variables

Python - Scope of Variables

Modules

Python - ModulesPython - Math ModulePython - JSON ModulePython - datetime ModulePython - time Module

I/O

Python - Read input from keyboard

File

Python - File Handling

Exception Handling

Python - Exception Handling

OOP

Python - Classes and ObjectsPython - Class Constructor __init__ methodPython - Class Destructor __del__ methodPython - Built-in Class AttributesPython - InheritancePython - Method OverridingPython - Method Overloading

Package Management

Python - PIP

Python - MySQL

Python - MySQL - Getting StartedPython - MySQL - Insert dataPython - MySQL - Select dataPython - MySQL - Update dataPython - MySQL - Delete data

Python - CSV

Python - Read data from CSV filePython - Write data in CSV file

Python - MySQL - Getting Started

Python

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()

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT