connect Postgres SQL in python

connect Postgres SQL in python

Pre-requisites:

  • Postgres database

  • Python

step -1

pip install psycopg2-binary

step -2

postgres credentials

host='localhost'
dbname='practice_db'
username='postgres'
password=123456
port=5432

step -3

import the pscopg2 module and use the connect function inside pscopg2 module

import psycopg2

# credentials 
host='localhost'
dbname='practice_db'
username='postgres'
password=123456
port=5432

# create connection
conn=psycopg2.connect(host=host, dbname=dbname, username=username, password=password, port=port)
conn.set_session(autocommit=True)
cur=conn.cursor()

cur.execute("select table_name, table_schem from information_schema.tables where table_schema='public'")

cur.close()
conn.close()

why have to close the session & cursor?

  • Resource Management: Each connection to a database consumes resources. If you don't close the connection, those resources remain in use, which can lead to performance issues

  • Data Integrity: Closing the connection ensures that any transactions are properly committed. (in case, if you want to connect multiple databases then you may do the wrong transaction if you didn't close that database connection.)

ย