Open In App

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 pyscopg2.connect() method. 



Syntax of update clause:

UPDATE "table"
SET "column_one" = value1, 
"column_two" = value2, 
"column_three" = valueN
WHERE condition;

Database Used

Below is the implementation:




import psycopg2
  
conn = psycopg2.connect(
    database="classroom_database",
      user='postgres', password='pass',
    host='127.0.0.1', port='5432'
)
  
conn.autocommit = True
cursor = conn.cursor()
  
  
sql = ''' update  student_details  set
          cgpa = 9.5 ,
          branch = 'AE'
        where student_name = 'rahul';'''
  
cursor.execute(sql)
  
sql1 = '''select * from student_details;'''
cursor.execute(sql1)
  
for i in cursor.fetchall():
    print(i)
  
conn.commit()
conn.close()

Output:



(12124468, 'arjun', 9.7, 'arjun19@gmail.com', 'CSE')
(12124469, 'DIYA', 9.4, 'diya@gmail.com', 'CSE')
(12124466, 'sarah', 9.8, 'sarah1212@gmail.com', 'CSE')
(12124470, 'priya', 8.8, 'priya@gmail.com', 'CSE')
(12124467, 'rahul', 9.5, 'rahul9@gmail.com', 'AE')

Output in PostgreSQL:

Article Tags :