📜  PostgreSQL Python – 更新表中的数据

📅  最后修改于: 2022-05-13 01:55:21.055000             🧑  作者: Mango

PostgreSQL Python – 更新表中的数据

在本文中,我们将了解如何使用Python的 pyscopg2 模块更新 PostgreSQL 表中的现有数据。

在 PostgreSQL 中,带有 where 子句的 UPDATE TABLE 用于从数据库更新现有表中的数据。

要执行任何 SQL 查询,execute()函数将使用要执行的 SQL 命令作为参数调用。

示范表:

下面是实现:

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()


更新记录后的表:

正如我们所见,州名已更新为哈里亚纳邦,其中名称为拉达。这意味着操作已成功完成。