Python Data Access 简明教程

Python SQLite - Drop Table

你可以使用 DROP TABLE 语句删除整个表。你只需指定要删除的表的名称即可。

You can remove an entire table using the DROP TABLE statement. You just need to specify the name of the table you need to delete.

Syntax

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

Following is the syntax of the DROP TABLE statement in PostgreSQL −

DROP TABLE table_name;

Example

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

Assume we have created two tables with name CRICKETERS and EMPLOYEES using the following queries −

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

现在,如果你使用 .tables 命令验证表格列表,就可以在其中看到上面创建的表格(列表)如下所示:

Now if you verify the list of tables using the .tables command, you can see the above created tables in it ( list) as −

sqlite> .tables
CRICKETERS EMPLOYEE
sqlite>

以下语句从数据库中删除名为 Employee 的表 −

Following statement deletes the table named Employee from the database −

sqlite> DROP table employee;
sqlite>

由于你已经删除了 Employee 表,因此如果你再次检索表列表,则只会在其中观察到一张表。

Since you have deleted the Employee table, if you retrieve the list of tables again, you can observe only one table in it.

sqlite> .tables
CRICKETERS
sqlite>

如果你再次尝试删除 Employee 表格,由于你已经删除了它,你将收到一个错误信息,显示“没有此表格”,如下所示:

If you try to delete the Employee table again, since you have already deleted it you will get an error saying “no such table” as shown below −

sqlite> DROP table employee;
Error: no such table: employee
sqlite>

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

To resolve this, you can use the IF EXISTS clause along with the DELTE statement. This removes the table if it exists else skips the DLETE operation.

sqlite> DROP table IF EXISTS employee;
sqlite>

Dropping a table using Python

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

You can drop a table whenever you need to, using the DROP statement of MYSQL, but you need to be very careful while deleting any existing table because the data lost will not be recovered after deleting a table.

Example

要使用 Python 从 SQLite3 数据库中删除表,请在游标对象上调用 execute() 方法,并将删除语句作为参数传递给它。

To drop a table from a SQLite3 database using python invoke the execute() method on the cursor object and pass the drop statement as a parameter to it.

import sqlite3

#Connecting to sqlite
conn = sqlite3.connect('example.db')

#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()

Output

Table dropped...