
- Python SQLite 教程
- Python SQLite - 主頁
- Python SQLite - 簡介
- Python SQLite - 建立連線
- Python SQLite - 建立表格
- Python SQLite - 插入資料
- Python SQLite - 選擇資料
- Python SQLite - Where 子句
- Python SQLite - Order By
- Python SQLite - 更新表格
- Python SQLite - 刪除資料
- Python SQLite - 刪除表格
- Python SQLite - Limit
- Python SQLite - Join
- Python SQLite - 游標物件
- Python SQLite 有用資源
- Python SQLite - 快速指南
- Python SQLite - 有用資源
- Python SQLite - 討論
Python SQLite - 刪除表格
可以使用 DROP TABLE 語句刪除整個表格。您只需指定需要刪除的表格名稱即可。
語法
以下是 PostgreSQL 中 DROP TABLE 語句的語法 −
DROP TABLE table_name;
示例
假設我們使用以下查詢建立了兩個名為 CRICKETERS 和 EMPLOYEES 的表格 −
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 命令驗證表格列表,則可以在其中看到上述建立的表格(列表),如下所示 −
sqlite> .tables CRICKETERS EMPLOYEE sqlite>
以下語句從資料庫中刪除名為 Employee 的表格 −
sqlite> DROP table employee; sqlite>
由於您已刪除了 Employee 表格,因此如果您再次檢索表格列表,您只能在其中看到一個表格。
sqlite> .tables CRICKETERS sqlite>
如果您嘗試再次刪除 Employee 表格,因為您已刪除了它,您會收到一條錯誤訊息,提示“此類表格不存在”,如下所示 −
sqlite> DROP table employee; Error: no such table: employee sqlite>
為解決此問題,您可以在 DELETE 語句中使用 IF EXISTS 子句。如果表格存在,它將移除表格,否則將跳過 DELETE 操作。
sqlite> DROP table IF EXISTS employee; sqlite>
使用 Python 刪除表格
您可以根據需要隨時使用 MYSQL 的 DROP 語句刪除表格,但在刪除任何現有表格時,您需要非常小心,因為在刪除表格後,丟失的資料將無法恢復。
示例
要使用 python 從 SQLite3 資料庫中刪除表格,請在游標物件上呼叫 execute() 方法,並將 drop 語句作為引數傳遞給該方法。
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()
輸出
Table dropped...
廣告