How to load data in PostgreSQL with Python

Below are the steps for loading data in PostgreSQL db with python. Python psycopg2 package is required for connectivity with PostgreSQL DB.

  • For laoding data in PostgreSQL DB Python3 needs to be installed on server, if Python3 is not installed refer the link How to install Python3.
  • For loading the data in PostgreSQL, we require database name, user name and password. if you have not configured the database user and password follow steps at link How to create database and new user in PostgreSQL.
  • If psycopg2 is not installed than install it with PIP
  • First we will create table in PostreSQL DB with Python and than will load data with Python.
  • Create python file and copy below code and run python code.
  • if you get error "psycopg2.OperationalError: FATAL: Ident authentication failed for user "test_user" while running the python code, refer the soltuion at solving ident issues in PostgreSQL
  • After creating table, create python file with code to load data into table, for this create python file and copy below code and run python code.
  • Check the loaded data in database.Connect postgres shell with below command and provide password
  • In the postgres shell run below command and you should be able to view three records.
  • Categories: Python