Create Your First PostgreSQL Database in Python With Psycopg2

Banner image


Today I am going to show you how to create and modify a PostgreSQL database in Python, with the help of the psycopg2 library.

Unlike SQLAlchemy that generates SQL queries while mapping the database schema to Python objects, psycopg2 takes your hand-crafted SQL queries and executes them against the database. In other words, SQLAlchemy is an ORM (Object-Relational Mapper) and psycopg2 is a database driver for PostgreSQL.

Create the database and its tables

We’ll be creating a dead simple housing database that consists of two tables: “person” and “house”.

houses database Entity-Relationship Diagram (created using DBeaver)

Each house has an address and multiple people can live in the same house (1 to many relationship/many people can live in a single house). This relationship is realized by using id as the primary key of “house” and house_id as the foreign key of “person”.

Now let’s see the complete script for the creation of the database and its tables, followed by an explanation of the code.

(in case you are not familiar with the if __name__ == "__main__" condition, it checks that the script being executed is the current script)

In essence, this script does the following:

  • Loads database connection information from a .ini file;
  • Connects to PostgreSQL;
  • Creates the “houses” database;
  • Connects to the newly-created database;
  • Creates the “house” table; and
  • Creates the “person” table.

The contents of the .ini file are just a set of variables for the database connection.



Think of it as storing API keys and other sensitive information in environment variables instead of hard-coding it in the script. Though since this is a local database it’s fine to show you my credentials.

After loading this information with the load_connection_info function as a dictionary (line 58 of the code gist), we connect to PostgreSQL. Because the database does not exist yet, we connect to the engine itself. The creation is handled by the create_db function (lines 16 to 36). psycopg2.connect returns a connection between Python and PostgreSQL, from which we create a cursor. Cursors are created to execute the code in the PostgreSQL.

After that, still in create_db, we execute the database creation query by passing it a string with the proper SQL code. This is wrapped in a try/except/else block in case something goes wrong. Usually we first execute the query and afterwards commit it to the database, but “CREATE DATABASE” statements require the commit to be automatic, hence using conn.autocommit in create_db.

Okay, the “houses” database is created, the next step is to create the “house” and “person” tables. First connect to the newly-created database on line 64 and create a new cursor on line 65. Instead of passing each argument separately (host, database, user and password), we use the ** operator to unpack each key-value pair on its own.

Then, we create the “house” and “person” tables. We write the necessary SQL queries and call the create_table function on lines 63 to 74 and 77 to 85, respectively. create_table simply executes and commits the queries, wrapped in a try/except/else block. If nothing bad happens, the changes are committed to the database inside the else block, otherwise the exception and query are output in the except block. In case an exception is raised we also rollback any changes that were not committed.

At the very end of the script we close all active connections and cursors.

#data-science #data #postgres #python #programming #psycopg2

What is GEEK

Buddha Community

Create Your First PostgreSQL Database in Python With Psycopg2
Ray  Patel

Ray Patel


top 30 Python Tips and Tricks for Beginners

Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.

1) swap two numbers.

2) Reversing a string in Python.

3) Create a single string from all the elements in list.

4) Chaining Of Comparison Operators.

5) Print The File Path Of Imported Modules.

6) Return Multiple Values From Functions.

7) Find The Most Frequent Value In A List.

8) Check The Memory Usage Of An Object.

#python #python hacks tricks #python learning tips #python programming tricks #python tips #python tips and tricks #python tips and tricks advanced #python tips and tricks for beginners #python tips tricks and techniques #python tutorial #tips and tricks in python #tips to learn python #top 30 python tips and tricks for beginners

Ray  Patel

Ray Patel


Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map

Kaia  Schmitt

Kaia Schmitt


How to Create Table in SQLite Database Python | Python Built-In Database - III

Create Table - Python Built-In Database - SQLite.

Github -

#sqlite #database #python #sqlite database python #database python

Kaia  Schmitt

Kaia Schmitt


How to Insert Records in SQLite Database Python | Python Built-In Database - IV

Insert Records - Python Built-In Database - SQLite.

Github -

#database #python #sqlite database python #sqlite #database python

Art  Lind

Art Lind


Python Tricks Every Developer Should Know

Python is awesome, it’s one of the easiest languages with simple and intuitive syntax but wait, have you ever thought that there might ways to write your python code simpler?

In this tutorial, you’re going to learn a variety of Python tricks that you can use to write your Python code in a more readable and efficient way like a pro.

Let’s get started

Swapping value in Python

Instead of creating a temporary variable to hold the value of the one while swapping, you can do this instead

>>> FirstName = "kalebu"
>>> LastName = "Jordan"
>>> FirstName, LastName = LastName, FirstName 
>>> print(FirstName, LastName)
('Jordan', 'kalebu')

#python #python-programming #python3 #python-tutorials #learn-python #python-tips #python-skills #python-development