Dynamically Update Multiple Rows with PostgreSQL and Python
Last Updated :
24 Apr, 2025
In this tutorial, we will explore how to dynamically update multiple rows in a PostgreSQL database using Python. By the end of this tutorial, you'll have a solid understanding of how to write efficient Python code that interacts with PostgreSQL to update multiple rows in a database. We'll cover topics such as connecting to a PostgreSQL database, executing SQL queries, and updating multiple rows using parameterized queries. So, whether you're a seasoned Python developer or just starting out, this tutorial will help you improve your skills and make you more productive when working with large datasets in PostgreSQL.
We can use the pyscopg2 library in Python for PostgreSQL.
Concept :
psycopg2 is a widely-used database adapter for PostgreSQL that allows Python programs to interact with PostgreSQL databases. This library offers a range of features, including.
- connection managementÂ
- SQL query executionÂ
- parameter bindingÂ
- transaction managementÂ
- error handling
- object-relational mapping.
With psycopg2, Python developers can easily connect to a PostgreSQL database by specifying the necessary parameters likeÂ
- hostname
- port number
- database nameÂ
- username
- password.Â
Once connected, they can execute SQL queries using the execute() method. The library also provides support for parameter binding, which helps prevent SQL injection attacks and makes it easier to write dynamic SQL queries.
psycopg2 offers robust transaction management functions, allowing developers to commit or roll back transactions using the commit() and rollback() methods of the connection object. Additionally, it includes an error-handling mechanism that allows developers to handle errors easily.
Finally, psycopg2 also supports object-relational mapping (ORM) frameworks like SQLAlchemy and Django ORM. Overall, psycopg2 is a powerful and flexible library for interacting with PostgreSQL databases from Python, and it has a large and active community of developers contributing to its development and maintenance.
General syntax :
The below python code is the basic outline of the code. We will have a look at the example further below.
Python3
import psycopg2
# Connection to the PostGreSql database
connection = psycopg2.connect(
host="host_name",
database="database_name",
user="username",
password="password"
)
# Creation of a cursor object
cursor = connection.cursor()
# Define the update statement with placeholders for dynamic data
update="UPDATE table_name SET column1 = %s, column2 = %s WHERE id = %s"
# Define the data to be updated
data = [
(value1,value2,id1),
(value1,value2,id2),
(value1,value2,id3),
# ...........
]
# Execute the update statement for each row of data
for row in data:
cursor.execute(update,row)
# Commit the changes to the database
connection.commit()
# Close the cursor and database connection
cursor.close()
connection.close()
Example :
Now let's consider a database named details, with column names [email, firstname, lastname, age]. Here email is the primary key.
Let's see the same in pgAdmin application.
PGAdmin ImageAs You can see, the table is not populated. Let's add some values now.
PGAdmin OutputCode :
Now let's change the values in the details' table using the python script.
Python3
import psycopg2
# Connection to the PostGreSql database
connection = psycopg2.connect(
host="localhost",
database="example",
user="postgres",
password="samexp"
)
# Creation of a cursor object
cursor = connection.cursor()
# Define the update statement with placeholders for dynamic data
update="UPDATE details SET firstname = %s, lastname = %s, age = %s WHERE email = %s"
data=[]
n=int(input("Enter n: "))
for i in range(n):
print("User - ",i," details: ")
email=input("Email: ")
fn=input("First name: ")
ln=input("Last name: ")
age=int(input("Age: "))
tup=(fn,ln,age,email)
data.append(tup)
# Execute the update statement for each row of data
for row in data:
cursor.execute(update,row)
# Commit the changes to the database
connection.commit()
print("completed")
# Close the cursor and database connection
cursor.close()
connection.close()
Input :
Terminal OutputNow, after executing the above script, we can see that the values have been changed.
Final output :
PGAdmin output
Similar Reads
Update multiple rows in same query in PostgreSQL using Pyscopg2-Python
In this article, we are going to update multiple rows in the same query in PostgreSQL using Pyscopg2in Python. We can update multiple values at once by using the update clause from PostgreSQL. First, we import the psycopg2 package and establish a connection to a PostgreSQL database using the pyscopg
1 min read
How to Update Multiple Rows in PostgreSQL?
In PostgreSQL, the UPDATE statement is a powerful tool used to modify existing records within a table. We appoint two sorts of examples: the primary includes updating based totally on a single condition, while the second relates to updating based totally on multiple conditions. Throughout this artic
5 min read
PostgreSQL Python - Update Data in Table
In this article, we are going to see how to update existing data in PostgreSQL tables using the pyscopg2 module in Python. In PostgreSQL, the UPDATE TABLE with where clause is used to update the data in the existing table from the database. Syntax: UPDATE <table_name> SET column1 = value1, c
2 min read
Insert Multiple Rows in MySQL Table in Python
MySQL is an open-source, Relational Database Management System (RDBMS) that stores data in a structured format using rows and columns. It is software that enables users to create, manage, and manipulate databases. So this is used in various applications across a wide range of industries and domains.
5 min read
How to Insert Multiple Rows to a Table in PostgreSQL?
Inserting multiple rows into a table in PostgreSQL is a common and efficient operation, especially when handling large datasets. By executing a single SQL query, multiple rows can be added simultaneously, reducing overhead and enhancing performance. This method is particularly valuable in scenarios
5 min read
PostgreSQL - Insert Multiple Values in Various Rows
PostgreSQL, one of the most popular relational database management systems (RDBMS), is widely used for storing structured data in a tabular format, much like MySQL. In relational databases, data is stored in tables where each row represents a record and each column represents an attribute. One of th
3 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
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
Bulk update of rows in Postgres DB using psycopg2
PostgreSQL or Postgres is an open-source, relational, SQL complaint, database management system. It allows, the developers, to create complex applications, supporting SQL and JSON querying. It safely stores, and, scales workloads. Psycopg2 is a driver, that is used, for interacting, with Postgres da
6 min read
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 .
1 min read