Python | Getting started with psycopg2-PostGreSQL

PostgreSQL is a powerful, open source object-relational database system. PostgreSQL runs on all major operating systems. PostgreSQL follows ACID property of DataBase system and has the support of triggers, updatable views and materialized views, foreign keys.

To connect PostgreSQL we use psycopg2 . It is the best and most friendly Database adapter in python language. It is both Unicode and Python3 friendly.

Installation Required –



 pip install psycopg2 

Let’s get started and understand PostgreSQL connection in parts.

Step #1: Connection to PostGreSQL

filter_none

edit
close

play_arrow

link
brightness_4
code

import psycopg2
conn = psycopg2.connect(database ="gfgdb", user = "gfguser",
                        password = "passgeeks", host = "52.33.0.1"
                        port = "5432")
  
print("Connection Successful to PostgreSQL")

chevron_right


 
Step #2: Declare Cursor

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

filter_none

edit
close

play_arrow

link
brightness_4
code

cur = conn.cursor()

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

query = """select name, email from geeks_members;"""
cur.execute(query)
rows = cur.fetchall()
  
# Now 'rows' has all data
for x in rows:
    print(x[0], x[1])

chevron_right


 
Step #4: Close the connection

filter_none

edit
close

play_arrow

link
brightness_4
code

conn.close()
print('Connection closed')

chevron_right




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.