Sunday, November 17, 2024
Google search engine
HomeLanguagesPostgreSQL Python – Update Data in Table

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, column2 = value2,….. WHERE [condition]

To execute any SQL query execute() function is called with the SQL command to be executed as a parameter.

Syntax: execute(SQL command)

Table for demonstration:

Below is the implementation:

Python3




# importing psycopg2 module
import psycopg2
  
# establishing the connection
conn = psycopg2.connect(
    database="postgres",
    user='postgres',
    password='password',
    host='localhost',
    port='5432'
)
  
# creating cursor object
cursor = conn.cursor()
  
# creating table
sql = '''CREATE TABLE Geeky(
 id  SERIAL NOT NULL,
 name varchar(20) not null,
 state varchar(20) not null
)'''
cursor.execute(sql)
  
# inserting values in it
cursor.execute('''INSERT INTO Geeky(name , state)\
    VALUES ('Babita','Bihar')''')
cursor.execute(
    '''INSERT INTO Geeky(name , state)\
    VALUES ('Anushka','Hyderabad')''')
cursor.execute(
    '''INSERT INTO Geeky(name , state)\
    VALUES ('Anamika','Banglore')''')
cursor.execute('''INSERT INTO Geeky(name , state)\
    VALUES ('Sanaya','Pune')''')
cursor.execute(
    '''INSERT INTO Geeky(name , state)\
    VALUES ('Radha','Chandigarh')''')
  
# query to update the existing record
# update state as Haryana where name is Radha
sql1 = "UPDATE Geeky SET state = 'Haryana' WHERE name = 'Radha'"
cursor.execute(sql1)
  
# Commit your changes in the database
conn.commit()
  
# Closing the connection
conn.close()


Table after updating the record:

As we can see state name has been updated to Haryana where the name is Radha. It means the operation has been successfully completed.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments