python清除数据库表命令_Python PostgreSQL-删除表

您可以使用DROP TABLE语句从PostgreSQL数据库中删除表。

句法

以下是PostgreSQL中DROP TABLE语句的语法-

DROP TABLE table_name;

假设我们使用以下查询创建了两个名为CRICKETERS和EMPLOYEES的表-

postgres=#CREATE TABLE CRICKETERS(First_NameVARCHAR(255),Last_NameVARCHAR(255),Ageint,Place_Of_BirthVARCHAR(255),CountryVARCHAR(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=#

要解决此问题,可以将IF EXISTS子句与DELTE语句一起使用。如果存在该表,则将其删除,否则将跳过DLETE操作。

postgres=#DROP table IF EXISTS employee;NOTICE:table"employee"doesnotexist,skipping

DROP TABLE

postgres=#

使用Python删除整个表格

您可以根据需要使用DROP语句删除表。但是删除任何现有表时需要非常小心,因为删除表后丢失的数据将无法恢复。

importpsycopg2#establishing the connectionconn=psycopg2.connect(database="mydb",user='postgres',password='password',host='127.0.0.1',port='5432')#Setting auto commit falseconn.autocommit=True#Creating a cursor object using the cursor() methodcursor=conn.cursor()#Doping EMPLOYEE table if already existscursor.execute("DROP TABLE emp")print("Table dropped... ")#Commit your changes in the databaseconn.commit()#Closing the connectionconn.close()

输出量

#Table dropped...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值