How To Connect and run SQL Queries to a PostgreSQL Database from Python
Last Updated :
19 Nov, 2024
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:
- Using pgAdmin 4 UI
- 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.
Create Database from side menu pop-up2. 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 commandStep 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
Python Script ExampleConclusion
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.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Spring Boot Interview Questions and Answers Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read