Python and MySQL Introduction

MySQL is a database that can be used in conjunction with Python to create desktop, web and console based application. It can be used to store data, as well as configuration information. Python, together with SQL, can be used to query the data stored within a MySQL database, as well as insert, update and delete the data.

Connecting to a MySQL Database

In order to access data within a MySQL database using Python, a connection to the database must first be established. Below is an example of how this can be achieved. In order for this to work, the third-party module PyMySQL must be installed.

import pymysql

# Database connection variable.
connect = None

# Database connection arguments.
connectargs = {
    'host': 'localhost',
    'database': 'testDB',
    'user': 'testUN',
    'password': 'testPW'


    # Connect to database.
    connect = pymysql.connect(**connectargs)

    # Message confirming successful database connection.
    print("Database connection successful.")

except pymysql.DatabaseError as e:

    # Message confirming unsuccessful database connection.
    print("Database connection unsuccessful.")

    # Stop program execution.

In this example, a ‘try-except’ block is used to catch any exceptions that may arise in connecting to the database. A ‘try-except’ block can be used to handle any exceptions in a user friendly manner. The ‘quit’ statement, after the confirmation of an unsuccessful database connection, stops execution of the program completely, so no further statements are executed.

The database connection arguments, which include the server and database information, are contained within a dictionary and then incorporated into the database connection, using the shorthand method, ‘**connectargs’. It should be noted that this information can be incorporated directly into the database connection. It much depends on personal preference and whether the dictionary is going to be re-used elsewhere in the program. The database connection can be re-written as follows.

# Connect to database.
connect = pymysql.connect(host='localhost', db='testDB',
                          user='testUN', passwd='testPW')