In this article, you will learn how to connect with the Postgres database in python programming language. We are going to write the sample code for each step and then will explain that piece of code.

In Python, it is very easy to use any package and then with the help of that package we can achieve our requirements.

Step 1: Import all the required packages.

import os
import psycopg2

Step 2: Store your database connection string in the DATABASE_URL variable and then create the cursor.

DATABASE_URL = 'Your database url string given in the heroku postgres setting'
conn = psycopg2.connect(DATABASE_URL, sslmode='require')
cur = conn.cursor()

Step 3: Execute the select statement query with the cursor object created in the above step and based on the result of the select query create a database table.

# Create employee Table
 cur.execute("select * from information_schema.tables where table_name=%s", ('employee',))
 table_exist = bool(cur.rowcount)
 if not table_exist:
     cur.execute('''CREATE TABLE employee
           (ID INT PRIMARY KEY     NOT NULL,
           emp_name           VARCHAR(256),
           emp_dept           VARCHAR(256) );''')

     print("Table employee created successfully")
 else:
     print("Table already exist")
 conn.commit()

If you face any issue in the execution of the above implementation, feel free to let us know by comments.

Happy Coding !!