📜  Python PostgreSQL – 删除数据(1)

📅  最后修改于: 2023-12-03 15:18:58.422000             🧑  作者: Mango

Python PostgreSQL – 删除数据

在Python中使用PostgreSQL数据库可以很容易地删除数据。下面是一些示例代码,展示如何在Python中删除PostgreSQL数据库中的数据。

1. 删除单个行

以下代码演示了如何在Python中删除单个行:

import psycopg2

try:
    connection = psycopg2.connect(user="username",
                                  password="password",
                                  host="localhost",
                                  port="5432",
                                  database="database_name")

    cursor = connection.cursor()
    delete_query = """DELETE FROM table_name WHERE column_name = value"""
    cursor.execute(delete_query)
    connection.commit()
    print("Row deleted successfully")

except (Exception, psycopg2.Error) as error:
    print("Error deleting row from PostgreSQL table", error)

finally:
    if (connection):
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")

请注意,此代码块需要将表名和列名更改为所需的值。

2. 删除多个行

以下代码演示了如何在Python中删除多个行:

import psycopg2

try:
    connection = psycopg2.connect(user="username",
                                  password="password",
                                  host="localhost",
                                  port="5432",
                                  database="database_name")

    cursor = connection.cursor()
    delete_query = """DELETE FROM table_name WHERE column_name IN (value1, value2, value3)"""
    cursor.execute(delete_query)
    connection.commit()
    print(cursor.rowcount, "Rows deleted successfully")

except (Exception, psycopg2.Error) as error:
    print("Error deleting rows from PostgreSQL table", error)

finally:
    if (connection):
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")

请注意,此代码块需要将表名、列名和值更改为所需的值。

3. 删除整个表

以下代码演示了如何在Python中删除整个表:

import psycopg2

try:
    connection = psycopg2.connect(user="username",
                                  password="password",
                                  host="localhost",
                                  port="5432",
                                  database="database_name")

    cursor = connection.cursor()
    delete_query = """DROP TABLE table_name"""
    cursor.execute(delete_query)
    connection.commit()
    print("Table deleted successfully")

except (Exception, psycopg2.Error) as error:
    print("Error deleting table from PostgreSQL database", error)

finally:
    if (connection):
        cursor.close()
        connection.close()
        print("PostgreSQL connection is closed")

请注意,此代码块需要将表名更改为所需的值。

总结

这些示例展示了如何在Python中删除PostgreSQL数据库中的数据。确保熟悉你的代码,并在运行之前进行必要的更改。