Python PostgreSQL - 刪除表格



可以使用 DROP TABLE 語句從 PostgreSQL 資料庫中刪除一個表格。

語法

以下是在 PostgreSQL 中 DROP TABLE 語句的語法 −

DROP TABLE table_name;

示例

假設已使用以下查詢建立了兩個名為 CRICKETERS 和 EMPLOYEES 的表格 −

postgres=# CREATE TABLE CRICKETERS (
   First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, 
   Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);
CREATE TABLE
postgres=#
postgres=# CREATE TABLE EMPLOYEE(
   FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), 
   AGE INT, SEX CHAR(1), INCOME FLOAT
);
CREATE TABLE
postgres=#

現在,如果你使用“\dt”命令驗證表格列表,可以看到上面建立的表格,如下 −

postgres=# \dt;
            List of relations
 Schema | Name       | Type  | Owner
--------+------------+-------+----------
 public | cricketers | table | postgres
 public | employee   | table | postgres
(2 rows)
postgres=#

以下語句從資料庫中刪除 Employee 表 −

postgres=# DROP table employee;
DROP TABLE

既然已刪除 Employee 表,如果你再次檢索表格列表,你只能看到一個表格。

postgres=# \dt;
            List of relations
Schema  | Name       | Type  | Owner
--------+------------+-------+----------
public  | cricketers | table | postgres
(1 row)


postgres=#

如果你嘗試再次刪除 Employee 表,由於已將其刪除,因此會收到提示“表不存在”的錯誤,如下所示 −

postgres=# DROP table employee;
ERROR: table "employee" does not exist
postgres=#

為了解決此問題,可以在 DELETE 語句中使用 IF EXISTS 子句。如果存在該表,則移除該表;否則,跳過 DLETE 操作。

postgres=# DROP table IF EXISTS employee;
NOTICE: table "employee" does not exist, skipping
DROP TABLE
postgres=#

使用 Python 移除整個表格

你可以隨時使用 DROP 語句刪除一個表格。但是,刪除任何現有表格時要非常小心,因為刪除表格後丟失的資料將無法恢復。

import psycopg2
#establishing the connection
conn = psycopg2.connect(database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432')

#Setting auto commit false
conn.autocommit = True

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Doping EMPLOYEE table if already exists
cursor.execute("DROP TABLE emp")
print("Table dropped... ")

#Commit your changes in the database
conn.commit()

#Closing the connection
conn.close()

輸出

#Table dropped...
廣告