Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python SQLite - Connecting to Database
Next article icon

PostgreSQL – Connecting to the Database using Python

Last Updated : 04 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

PostgreSQL in Python offers a robust solution for developers looking to interact with databases seamlessly. With the psycopg2 tutorial, we can easily connect Python to PostgreSQL, enabling us to perform various database operations efficiently. In this article, we will walk you through the essential steps required to use PostgreSQL in our Python applications.

PostgreSQL – Connecting to the Database using Python

To get started, we first need to ensure that we have the psycopg2 package installed. This package serves as the PostgreSQL database adapter for Python, allowing us to communicate with our PostgreSQL database effectively.

Prerequisites for Using psycopg2

Before diving into the examples, ensure we have Python installed on our system. We will need the psycopg2 module, which can be installed using the following command in our command prompt or terminal:

pip install psycopg2

Alternatively, for a more straightforward installation that doesn’t require a compiler, we can use:

pip install psycopg2-binary

Creating a PostgreSQL Database

For the purpose of example we will be needing a sample database. To create so, follow the below steps:

  1. First open a PostgreSQL client tool like pgadmin4 or psql.
  2. Second login to the database using your credentials.
  3. Finally use the below command to create a database (say, School)
CREATE DATABASE school;

Connecting to the database

To connect to the above created database (ie, school), we use the connect () function. The connect() function is used to create a new database session and it returns a new connection class instance.

Basic Connection Example

Use the following syntax to connect:

import psycopg2

# Connect to the School database
conn = psycopg2.connect(
dbname="school",
user="postgres",
password="your_password",
host="localhost"
)

Using a Configuration File

To make your connection more convenient and secure, we can use a configuration file. Create a file named database.ini with the following content:

[postgresql]
host=localhost
database=school
user=postgres
password=your_password

Now, the following config() function reads the database.ini file and returns connection parameters. The same config() function is added in the config.py file:

#!/usr/bin/python
from configparser import ConfigParser


def config(filename='database.ini', section='postgresql'):
# create a parser
parser = ConfigParser()
# read config file
parser.read(filename)

# get section, default to postgresql
db = {}
if parser.has_section(section):
params = parser.items(section)
for param in params:
db[param[0]] = param[1]
else:
raise Exception('Section {0} not found in the {1} file'.format(section, filename))

return db

Fetching PostgreSQL Version

The following connect() function connects to the school database that we created earlier and returns  the PostgreSQL database version.

#!/usr/bin/python
import psycopg2
from config import config

def connect():
""" Connect to the PostgreSQL database server """
conn = None
try:
# read connection parameters
params = config()

# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
conn = psycopg2.connect(**params)

# create a cursor
cur = conn.cursor()

# execute a statement
print('PostgreSQL database version:')
cur.execute('SELECT version()')

# display the PostgreSQL database server version
db_version = cur.fetchone()
print(db_version)

# close the communication with the PostgreSQL
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')


if __name__ == '__main__':
connect()

Output

PostgreSQL-Version-Output

PostgreSQL Version Output

Conclusion

In this article, we explored how to create a PostgreSQL database with Python and manage PostgreSQL databases with Python using the psycopg2 module. This powerful PostgreSQL database adapter for Python streamlines the process of interacting with our database, allowing us to perform operations efficiently. Mastering these skills will undoubtedly enhance our capabilities as a developer working with data.



Next Article
Python SQLite - Connecting to Database

D

ddeevviissaavviittaa
Improve
Article Tags :
  • Databases
  • PostgreSQL
  • Python
  • postgreSQL-administration
  • postgreSQL-managing-database
Practice Tags :
  • python

Similar Reads

  • Connecting to SQL Database using SQLAlchemy in Python
    In this article, we will see how to connect to an SQL database using SQLAlchemy in Python. To connect to a SQL database using SQLAlchemy we will require the sqlalchemy library installed in our python environment. It can be installed using pip - !pip install sqlalchemyThe create_engine() method of sq
    3 min read
  • Python SQLite - Connecting to Database
    In this article, we'll discuss how to connect to an SQLite Database using the sqlite3 module in Python. Connecting to the Database Connecting to the SQLite Database can be established using the connect() method, passing the name of the database to be accessed as a parameter. If that database does no
    2 min read
  • PostgreSQL - Create table using Python
    Creating tables in a PostgreSQL database using Python is a common task for developers working with databases. This process involves defining the structure of your data and ensuring that your database is optimized for efficient storage and retrieval. In this article, we will walk through the steps of
    3 min read
  • PostgreSQL - Connect To PostgreSQL Database Server in Python
    The psycopg database adapter is used to connect with PostgreSQL database server through python. Installing psycopg: First, use the following command line from the terminal: pip install psycopg If you have downloaded the source package into your computer, you can use the setup.py as follows: python s
    4 min read
  • Connect to MySQL using PyMySQL in Python
    In this article, we will discuss how to connect to the MySQL database remotely or locally using Python. In below process, we will use PyMySQL module of Python to connect our database. What is PyMySQL? This package contains a pure-Python MySQL client library, based on PEP 249. Requirements : MySQL Se
    2 min read
  • How to Connect Python with SQL Database?
    In this article, we will learn how to connect SQL with Python using the MySQL Connector Python module. Below diagram illustrates how a connection request is sent to MySQL connector Python, how it gets accepted from the database and how the cursor is executed with result data. To create a connection
    2 min read
  • Connecting PostgreSQL with SQLAlchemy in Python
    In this article, we will discuss how to connect PostgreSQL with SQLAlchemy in Python. In order to connect with any Database management system, it is essential to create an engine object, that serves as a central source of connection by providing a connection pool that manages the database connection
    3 min read
  • Connect MySQL database using MySQL-Connector Python
    While working with Python we need to work with databases, they may be of different types like MySQL, SQLite, NoSQL, etc. In this article, we will be looking forward to how to connect MySQL databases using MySQL Connector/Python.MySQL Connector module of Python is used to connect MySQL databases with
    3 min read
  • Python PostgreSQL Connection Pooling Using Psycopg2
    In this article, We will cover the basics of connection pooling using connection pooling in Python applications, and provide step-by-step instructions on how to implement connection pooling using Psycopg2. Whether you are building a small-scale application or a large-scale enterprise application, un
    6 min read
  • How to Log Queries in PostgreSQL using Python?
    Python has various database drivers for PostgreSQL. Current most used version is psycopg2. It fully implements the Python DB-API 2.0 specification. The psycopg2 provides many useful features such as client-side and server-side cursors, asynchronous notification and communication, COPY command suppor
    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