psycopg2-tutorial icon indicating copy to clipboard operation
psycopg2-tutorial copied to clipboard

:elephant: :floppy_disk: Tutorial for connecting to a Postgres database in Python.

Psycopg2 Tutorial

Python Psycopg2-Binary GitHub Last Commit GitHub Issues GitHub Stars GitHub Forks

Psycopg2-Tutorial

Source code for the accompanying tutorial found here: https://hackersandslackers.com/psycopg2-postgres-python/

Connect to a PostgreSQL database and execute queries in Python using the Psycopg2 library using this tutorial. This script looks for .sql files stored in the /queries directory, and executes them against a Postgres database.

Getting Started

Installation via requirements.txt:

$ git clone https://github.com/hackersandslackers/psycopg2-tutorial.git
$ cd psycopg2-tutorial
$ python3 -m venv myenv
$ source myenv/bin/activate
$ pip3 install -r requirements.txt
$ python3 main.py

Installation via Pipenv:

$ git clone https://github.com/hackersandslackers/psycopg2-tutorial.git
$ cd psycopg2-tutorial
$ pipenv shell
$ pipenv update
$ python3 main.py

Installation via Poetry:

$ git clone https://github.com/hackersandslackers/psycopg2-tutorial.git
$ cd psycopg2-tutorial
$ poetry shell
$ poetry update
$ poetry run

Usage

Replace the values in .env.example with your values and rename this file to .env:

  • DATABASE_USERNAME: The username used to connect to your Postgres database.
  • DATABASE_PASSWORD: Password for the above user.
  • DATABASE_HOST: The hostname of your database (ie: localhost).
  • DATABASE_NAME: The name of your "database" (the database inside your database - why isn't there a better term for this?).
  • DATABASE_PORT: Port of your Postgres database (default is 5432).

Remember never to commit secrets saved in .env files to Github.


Hackers and Slackers tutorials are free of charge. If you found this tutorial helpful, a small donation would be greatly appreciated to keep us in business. All proceeds go towards coffee, and all coffee goes towards more content.