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 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:
How To Connect and run SQL Queries to a PostgreSQL Database from Python
Next article icon

How To Connect and run SQL Queries to a PostgreSQL Database from Python

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

In this PostgreSQL Python tutorial, we will explain how to connect to a PostgreSQL database using Python and execute SQL queries. Using the powerful psycopg2 library, we can seamlessly interact with our PostgreSQL database from Python, making it easy to perform tasks like inserting, updating, and retrieving data.

Whether we're new to Python or a seasoned developer, mastering these techniques will enhance our ability to manage and manipulate data directly within our PostgreSQL database. In this article, we will walk us through the process of connecting to a PostgreSQL database using Python, running SQL queries, and handling results effectively.

Introduction to PostgreSQL and Python Integration

PostgreSQL is a widely-used open-source relational database management system known for its scalability, robustness, and advanced features. Python, with its flexibility, makes database connectivity seamless through libraries like psycopg2, enabling developers to interact with PostgreSQL databases for executing SQL queries.

Step 1: Install psycopg2 Library

The psycopg2 library is the most popular and widely used PostgreSQL adapter for Python.

  • Install PostgreSQL, If you haven't installed it.
  • We need to install the psycopg2 library to connect to a PostgreSQL database. Open the command prompt and run the below command to install psycopg2
pip3 install psycopg2

Step 2: Create a PostgreSQL Database

To interact with a database, we need a PostgreSQL database. We can create a Database in 2 Ways:

  1. Using pgAdmin 4 UI
  2. Using SQL query

1. Using pgAdmin 4 UI

Go to pgAdmin and Follow these Steps.

  • Open pgAdmin and navigate to your server.
  • Right-click on the server, select Create -> Database.
  • Fill out the form (e.g., database name: Workspace) and click Save.
Connect and run SQL queries to a PostgreSQL database from Python
Create Database from side menu pop-up

2. Create Database Using SQL query

Go to pgAdmin and follow these Steps. Run the below Command in the Query tab

CREATE DATABASE WorkSpace;
Run the create database command

Step 3: Connect to PostgreSQL Database Using psycopg2

We need to connect to a PostgreSQL database using psycopg2.connect() function.

Where the attributes of connect() function are:

  • host: Hostname (e.g., localhost)
  • dbname: Database name
  • user: Username
  • password: Password
  • port: Port number (default is 5432)

In case we don't know any of these connect() function attributes, we can follow the below steps:

 
 

Python Example: Establishing Connection

Now You Know All the properties of this Database. To connect to the database, we need to pass the attributes as arguments to the connect() function.

Syntax

conn = psycopg2.connect(
host = 'localhost',
dbname = 'For_Practice',
user = 'postgres',
password = '[Password]',
port = 5432
)

Step 4: Create a Cursor

  • Create a cursor(i.e., curr) object and call its execute() method to execute queries.
  • Where execute() method is used to run a query that is passed as a string.

Syntax

cur = conn.cursor()
cur.execute('[SQL queries]')

Step 5: Close the Connection

In the end, We need to save the changes using commit() method and finally close the opened connection using close() method.

Syntax

conn.commit()
cur.close()

Complete Python Script Example

import psycopg2

conn = None
try:
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
conn = psycopg2.connect(
host = 'localhost',
dbname = 'For_Practice',
user = 'postgres',
password = '321654',
port = 5432
)

# Creating a cursor with name cur.
cur = conn.cursor()
print('Connected to the PostgreSQL database')

# Execute a query:
# To display the PostgreSQL
# database server version
cur.execute('SELECT version()')
print(cur.fetchone())

# Close the connection
cur.close()

except(Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')

Output

Output2
Python Script Example

Conclusion

In conclusion, the psycopg2 library in Python is an essential tool for establishing a seamless Python PostgreSQL database connection and running SQL queries directly from our Python code. By mastering these techniques, we can efficiently manage and manipulate data in PostgreSQL databases, allowing for better integration of database operations into our Python applications. Whether for development or data analysis, this powerful combination enhances our productivity and workflow.


Next Article
How To Connect and run SQL Queries to a PostgreSQL Database from Python
author
ayonssp
Improve
Article Tags :
  • Python
  • PostgreSQL
  • Databases
Practice Tags :
  • python

Similar Reads

    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
    PostgreSQL - Connecting to the Database using Python
    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
    4 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.SQL connection with Pyth
    2 min read
    How to connect to SQLite database that resides in the memory using Python ?
    In this article, we will learn how to Connect an SQLite database connection to a database that resides in the memory using Python. But first let brief about what is sqlite. SQLite is a lightweight database software library that provides a relational database management system. Generally, it is a ser
    3 min read
    How to Convert SQL Query Results to Pandas Dataframe Using pypyodbc?
    In this article, we are going to see how to convert SQL Query results to a Pandas Dataframe using pypyodbc module in Python. We may need database results from the table using different queries to work on the data and apply any machine learning on the data to analyze the things and the suggestions be
    2 min read
    Sending data from a Flask app to PostgreSQL Database
    A database is used to store and maintain persistent data that can be retrieved and manipulated efficiently. we usually need a database, an organized collection of data for example in an e-commerce web app where we need to store the data about the users, orders, carts, shipping, etc. In a database, d
    6 min read
    PostgreSQL - Connect and Access a Database
    In this article, we will learn about how to access the PostgreSQL database. Once the database is created in PostgreSQL, we can access it in two ways using: psql: PostgreSQL interactive terminal program, which allows us to interactively enter, edit, and execute SQL commands.pgAdmin: A graphical front
    3 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
    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
    How to List Databases and Tables in PostgreSQL using PSQL
    PostgreSQL is a powerful, open-source object-relational database system. It provides a wide array of tools and features to manage databases, tables, and other database objects. In this article, we will explain how to list databases and tables in PostgreSQL using the psql command-line interface. We w
    3 min read
top_of_element && top_of_screen < bottom_of_element) || (bottom_of_screen > articleRecommendedTop && top_of_screen < articleRecommendedBottom) || (top_of_screen > articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
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