Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Database
  • Python MySQL
  • Python SQLite
  • Python MongoDB
  • PostgreSQL
  • SQLAlchemy
  • Django
  • Flask
  • SQL
  • ReactJS
  • Vue.js
  • AngularJS
  • API
  • REST API
  • Express.js
  • NodeJS
Open In App
Next Article:
Python | Database management in PostgreSQL
Next article icon

Python | Database management in PostgreSQL

Last Updated : 28 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report
PostgreSQL is an open source object-relational database management system. It is well known for its reliability, robustness, and performance. PostgreSQL has a variety of libraries of API (Application programmable interface) that are available for a variety of popular programming languages such as Python. It provides a lot of features for Database management such as Views, Triggers, Indexes (using B-Trees), etc. There are several python modules that allow us to connect to and manipulate the database using PostgreSQL:
  • Psycopg2
  • pg8000
  • py-postgresql
  • PyGreSQL
Psycopg2 is one of the most popular python drivers for PostgreSQL. It is actively maintained and provides support for different versions of python. It also provides support for Threads and can be used in multithreaded applications. For these reasons, it is a popular choice for developers. In this article, we shall explore the features of PostgreSQl using psycopg2 by building a simple database management system in python. Installation:
sudo pip3 install psycopg2 
Note: if you are using Python2, use pip install instead of pip3 Once psycopg has been installed in your system, we can connect to the database and execute queries in Python.

Creating the database

before we can access the database in python, we need to create the database in postgresql. To create the database, follow the steps given below:
  1. Log in to PostgreSQL:
    sudo -u postgres psql
  2. Configure the password:
    \password
    You will then be prompted to enter the password. remember this as we will use it to connect to the database in Python.
  3. Create a database called "test". we will connect to this database.
    CREATE DATABASE test; 
    Once the database and password have been configured, exit the psql server.
  4. Connecting to the database

    The connect() method is used to establish connection with the database. It takes 5 parameters:
    1. database: The name of the database you are connecting to
    2. user: the username of your local system
    3. password: the password to log in to psql
    4. host: The host, which is set to localhost by default
    5. port: The port number which is 5432 by default
    conn = psycopg2.connect(              database="test",               user = "adith",               password = "password",               host = "localhost",               port = "5432")
    Once the connection has been established, we can manipulate the database in python. The Cursor object is used to execute sql queries. we can create a cursor object using the connecting object (conn)
     cur = conn.cursor()  
    Using this object, we can make changes to the database that we are connected to. After you have executed all the queries, we need to disconnect from the connection. Not disconnecting will not cause any errors but it is generally considered a good practice to disconnect.
     conn.close() 

    Executing queries

    The execute() method takes in one parameter, the SQL query to be executed. The SQL query is taken in the form of a string that contains the SQL statement.
     cur.execute("SELECT * FROM emp") 

    Fetching the data

    Once the query has been executed, the results of the query can be obtained using the fetchall() method. This method takes no parameters and returns the result of select queries.
     res = cur.fetchall() 
    The result of the query is stored in the res variable.

    Putting it all together

    Once we have created the database in PostgreSQL, we can access that database in python. We first create an emp table in the database called test with the schema: (id INTEGER PRIMARY KEY, name VARCHAR(10), salary INT, dept INT). Once the table is created without any errors, we insert values into the table. Once the values are inserted, we can query the table to select all the rows and display them to the user using the fetchall() function. Python3 1==
    # importing libraries import psycopg2  # a function to connect to # the database. def connect():      # connecting to the database called test     # using the connect function     try:          conn = psycopg2.connect(database ="test",                              user = "adith",                              password = "password",                              host = "localhost",                              port = "5432")          # creating the cursor object         cur = conn.cursor()          except (Exception, psycopg2.DatabaseError) as error:                  print ("Error while creating PostgreSQL table", error)           # returning the conn and cur     # objects to be used later     return conn, cur   # a function to create the  # emp table. def create_table():      # connect to the database.     conn, cur = connect()      try:         # the test database contains a table called emp           # the schema : (id INTEGER PRIMARY KEY,           # name VARCHAR(10), salary INT, dept INT)          # create the emp table           cur.execute('CREATE TABLE emp (id INT PRIMARY KEY, name VARCHAR(10),                                        salary INT, dept INT)')          # the commit function permanently         # saves the changes made to the database         # the rollback() function can be used if         # there are any undesirable changes and         # it simply undoes the changes of the         # previous query          except:          print('error')      conn.commit()     # a function to insert data # into the emp table def insert_data(id = 1, name = '', salary = 1000, dept = 1):      conn, cur = connect()      try:         # inserting values into the emp table         cur.execute('INSERT INTO emp VALUES(%s, %s, %s, %s)',                                     (id, name, salary, dept))          except Exception as e:          print('error', e)     # committing the transaction.     conn.commit()   # a function to fetch the data  # from the table def fetch_data():      conn, cur = connect()      # select all the rows from emp     try:         cur.execute('SELECT * FROM emp')          except:         print('error !')      # store the result in data     data = cur.fetchall()      # return the result     return data  # a function to print the data def print_data(data):      print('Query result: ')     print()      # iterating over all the      # rows in the table     for row in data:          # printing the columns         print('id: ', row[0])         print('name: ', row[1])         print('salary: ', row[2])         print('dept: ', row[3])         print('----------------------------------')  # function to delete the table def delete_table():      conn, cur = connect()      # delete the table     try:          cur.execute('DROP TABLE emp')      except Exception as e:         print('error', e)      conn.commit()   # driver function if __name__ == '__main__':      # create the table      create_table()      # inserting some values     insert_data(1, 'adith', 1000, 2)     insert_data(2, 'tyrion', 100000, 2)     insert_data(3, 'jon', 100, 3)     insert_data(4, 'daenerys', 10000, 4)      # getting all the rows     data = fetch_data()      # printing the rows     print_data(data)      # deleting the table     # once we are done with     # the program     delete_table() 
    Output :

    Next Article
    Python | Database management in PostgreSQL

    A

    Adith Bharadwaj
    Improve
    Article Tags :
    • Python
    • Python-database
    Practice Tags :
    • python

    Similar Reads

      Insert Python list into PostgreSQL database
      In this article, we will discuss how to Insert a Python list into PostgreSQL database using pyscopg2 module. Psycopg2 is the most popular PostgreSQL adapter for the Python programming language. Psycopg2 is a DB API 2.0 compliant PostgreSQL driver that is actively developed. It is designed for multi-
      2 min read
      Python PostgreSQL - Delete Data
      In this article, we are going to see how to delete data in tables from PostgreSQL using pyscopg2 module in Python. In PostgreSQL, DELETE TABLE is used to delete the data in the existing table from the database. It removes table definition and all associated data, indexes, rules, triggers, and constr
      2 min read
      Transactions management in PostgreSQL Python
      Psycopg is a PostgreSQL database adapter package for Python. It is a medium to communicate with PostgreSQL databases from Python applications. Transactions are a very essential feature of any database management system, including PostgreSQL. Psycopg helps with transactions, which allows to execution
      9 min read
      Save a image file on a Postgres database - Python
      In this article, we are going to see how to save image files on a postgresql database using Python.  Psycopg2 is a driver, that is used, for interacting, with Postgres data, using the Python scripting language. It is, used to perform, CRUD operations on Postgres data.  Data handled in applications c
      4 min read
      Python - Database Manager (dbm) package
      In this article, we will learn about dbm, a package in the built-in library of Python. The dbm package in Python provides a simple dictionary-like interface of the form DBM (DataBase Manager) generally used in the Unix operating system. dbm stores data in simple key-value pair form like a dictionary
      4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences