Python and PostgreSQL - Inserting Data

In order to insert data into a PostgreSQL database, the SQL ‘Insert’ statement needs to be used. The following example inserts a record into the same ‘person’ table that was used in the example for selecting data.

Inserting data works in a similar fashion as selecting data using parameters. Firstly, a connection to the database is established, then the query parameters are defined as variables, which are then bound in to the SQL statement when it is executed and a confirmation message is displayed. The execution of the SQL statement is wrapped in a ‘try-except-finally’ block to catch any errors that may arise and close the database connection at the end.

import psycopg2

# Database connection variable.
connect = None


    # Connect to database.
    connect = psycopg2.connect(host='localhost', database='Demo',
                               user='DemoUN', password='DemoPW;')

except psycopg2.DatabaseError as e:

    # Confirm unsuccessful connection and stop program execution.
    print("Database connection unsuccessful.")

# Cursor to execute query.
cursor = connect.cursor()

# Query parameters.
firstname = "Fiona"
lastname = "Jones"
title = "Miss"
dob = "1985-05-19"

# SQL to insert data into the person table.
sqlInsert = \
    "INSERT INTO person (firstname, lastname, title, dob)  \
     VALUES (%s, %s, %s, %s)"


    # Execute query and commit changes.
    cursor.execute(sqlInsert, (firstname, lastname, title, dob))

    # Confirm successful addition of person information.
    print("Person information added successfully.")

except psycopg2.DatabaseError as e:

    # Confirm error adding person information and stop program execution.
    print("Error adding person information.")


    # Close database connection.

The contents of the ‘person’ table now looks as follows.

id firstname lastname title dob
1 Bob Smith Mr 1980-01-20
2 George Jones Mr 1997-12-15
3 Fred Bloggs Mr 1975-05-07
4 Alan White Mr 1989-03-20
5 Fiona Jones Miss 1985-05-19