Python PostgreSQL – 删除数据
在本文中,我们将看到如何使用Python的pyscopg2 模块从 PostgreSQL 中删除表中的数据。在 PostgreSQL 中,DELETE TABLE 用于从数据库中删除现有表中的数据。它删除表定义以及该表的所有关联数据、索引、规则、触发器和约束。如果特定表不存在,则显示错误。
使用的表:
在这里,我们使用accounts 表进行演示。
现在让我们删除这个表,因为我们将使用 will psycopg2模块连接 PostgreSQL 并在 cursor.execute(query) 对象中执行 SQL 查询。
Syntax: cursor.execute(sql_query);
示例 1:删除表中的所有数据
这里我们使用 DELETE 子句删除所有表数据。
Syntax: DELETE FROM table_name
代码:
Python3
# importing psycopg2
import psycopg2
conn=psycopg2.connect(
database="geeks",
user="postgres",
password="root",
host="localhost",
port="5432"
)
# Creating a cursor object using the cursor()
# method
cursor = conn.cursor()
# delete all details from account table
sql = ''' DELETE FROM account '''
# Executing the query
cursor.execute(sql)
# Commit your changes in the database
conn.commit()
# Closing the connection
conn.close()
Python3
# importing psycopg2
import psycopg2
conn=psycopg2.connect(
database="geeks",
user="postgres",
password="password",
host="localhost",
port="5432"
)
# Creating a cursor object using the cursor()
# method
cursor = conn.cursor()
# delete details of row where id =1 from account
# table
sql = ''' DELETE FROM account WHERE id='151' '''
# Executing the query
cursor.execute(sql)
# Commit your changes in the database
conn.commit()
# Closing the connection
conn.close()
输出:
示例 2:使用 where子句
where 子句在 SQL 中用作条件语句,用于过滤记录。
Syntax: DELETE FROM table_name FROM WHERE condition
代码:
蟒蛇3
# importing psycopg2
import psycopg2
conn=psycopg2.connect(
database="geeks",
user="postgres",
password="password",
host="localhost",
port="5432"
)
# Creating a cursor object using the cursor()
# method
cursor = conn.cursor()
# delete details of row where id =1 from account
# table
sql = ''' DELETE FROM account WHERE id='151' '''
# Executing the query
cursor.execute(sql)
# Commit your changes in the database
conn.commit()
# Closing the connection
conn.close()
输出: