📜  Python PostgreSQL – 更新表

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

Python PostgreSQL – 更新表

在本文中,我们将看到如何使用Python和 Psycopg2 更新 PostgreSQL 中的数据。 update 命令用于修改表中现有的记录。默认情况下,修改特定属性的整个记录,但要修改某些特定行,我们需要使用 where 子句和 update 子句。

示范表:

示例1:使用Python更新表的列——pscopg2

在这里,我们将看到如何更新表的列。修改后的表格如下表所示。正如我们所看到的,每个元组状态值都更改为克什米尔。



Python3
# importing psycopg2 module
import psycopg2
  
# establishing the connection
conn = psycopg2.connect(
   database="postgres",
    user='postgres',
    password='password',
    host='localhost',
    port= '5432'
)
  
# creating a curssor object
cursor = conn.cursor()
  
# query to update table with where clause 
sql='''update Geeks set state='Kashmir'; '''
  
# execute the query
cursor.execute(sql)
print('table updated..')
  
print('table after updation...')
sql2='''select * from Geeks;'''
cursor.execute(sql2);
  
# print table after modification
print(cursor.fetchall())
  
# Commit your changes in the database
conn.commit()
  
# Closing the connection
conn.close()# code


Python3
# importing psycopg2 module
import psycopg2
  
# establishing the connection
conn = psycopg2.connect(
   database="postgres",
    user='postgres',
    password='password',
    host='localhost',
    port= '5432'
)
  
# create a cursor object
cursor = conn.cursor()
  
# query to update table
sql='''update Geeks set state='Delhi' where id='2'; '''
  
# execute the qury
cursor.execute(sql)
print("Table updated..")
  
print('Table after updation...')
  
# query to display Geeks table
sql2='select * from Geeks;'
  
# execute query
cursor.execute(sql2);
  
# fetching all details
print(cursor.fetchall());
  
# Commit your changes in the database
conn.commit()
  
# Closing the connection
conn.close()


输出

table updated..
table after updation...
[(1,'Babita','kashmir'),(2,'Anushka','Kashmir'),(3,'Anamika','Kashmir'),
(4,'Sanaya','Kashmir'),(5,'Radha','Kashmir')]

示例 2:使用 where 子句更新列

这里我们将使用 where 子句和更新表。

我们可以看到id 为2 的行的状态Hyderabad更改为Delhi

蟒蛇3

# importing psycopg2 module
import psycopg2
  
# establishing the connection
conn = psycopg2.connect(
   database="postgres",
    user='postgres',
    password='password',
    host='localhost',
    port= '5432'
)
  
# create a cursor object
cursor = conn.cursor()
  
# query to update table
sql='''update Geeks set state='Delhi' where id='2'; '''
  
# execute the qury
cursor.execute(sql)
print("Table updated..")
  
print('Table after updation...')
  
# query to display Geeks table
sql2='select * from Geeks;'
  
# execute query
cursor.execute(sql2);
  
# fetching all details
print(cursor.fetchall());
  
# Commit your changes in the database
conn.commit()
  
# Closing the connection
conn.close()

输出:

Table updated..
Table after updation...
[(1, 'Babita', 'Bihar'), (3, 'Anamika', 'Banglore'), 
(4, 'Sanaya', 'Pune'), (5, 'Radha', 'Chandigarh'),
 (2, 'Anushka', 'Delhi')]