+

Python | Getting started with psycopg2-PostGreSQL

We use psycopg2 to connect PostgreSQL. It is the best and most user-friendly Python database adapter. It is both Unicode and Python3 friendly.

Requires installation —

 pip install psycopg2 

Let`s get started and break the link with PostgreSQL piece by piece.

Step # 1: Connect to PostGreSQL

import psycopg2

conn = psycopg2.connect (database = " gfgdb " , user = "gfguser" ,

password = "passgeeks " , host = " 52.33.0.1 "  , 

port = "5432" )

 

print ( "Connection Successful to PostgreSQL" )

Step # 2: Declare a cursor

Allows Python code to execute a PostgreSQL command in a database session.

cur = conn.cursor ()

Step # 3: Write your SQL query and execute it.

que ry = & quot; & quot; & quot; choose name, email address from geeks_members; & quot; & quot; & quot;

cur.execute (query)

rows = cur.fetchall ()

 
# Now lines contain all data

for x in rows:

print (x [ 0 ], x [ 1 ])

Step # 4: Close the connection

conn.close ()

print ( `Connection c losed` )

Get Solution for free from DataCamp guru