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.
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 Cursor
Allows Python code to execute PostgreSQL command in a database session.
cur = conn.cursor() |
Step #3: Write your SQL Query and execute it.
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]) |
Step #4: Close the connection
conn.close() print('Connection closed') |
Recommended Posts:
- Getting started with Jupyter Notebook | Python
- Python | Getting started with SymPy module
- Check if a Thread has started in Python
- Getting started with Scikit-image: image processing in Python
- Python | Merge Python key values to list
- Reading Python File-Like Objects from C | Python
- Important differences between Python 2.x and Python 3.x with examples
- Python | Add Logging to Python Libraries
- Python | Add Logging to a Python Script
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Sort Python Dictionaries by Key or Value
- JavaScript vs Python : Can Python Overtop JavaScript by 2020?
- SHA in Python
- pow() in Python
- SQL using Python | Set 1
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.



