Python MySQL - 刪除表



您可以使用DROP TABLE語句刪除整個表。您只需要指定要刪除的表的名稱。

語法

以下是 MySQL 中 DROP TABLE 語句的語法:

DROP TABLE table_name;

示例

在刪除表之前,請使用 SHOW TABLES 語句獲取表的列表,如下所示:

mysql> SHOW TABLES;
+-----------------+
| Tables_in_mydb  |
+-----------------+
| contact         |
| cricketers_data |
| employee        |
| sample          |
| tutorials       |
+-----------------+
5 rows in set (0.00 sec)

以下語句將完全從資料庫中刪除名為 sample 的表:

mysql> DROP TABLE sample;
Query OK, 0 rows affected (0.29 sec)

由於我們已從 MySQL 中刪除了名為 sample 的表,因此如果您再次獲取表的列表,將不會在其中找到表名 sample。

mysql> SHOW TABLES;
+-----------------+
| Tables_in_mydb  |
+-----------------+
| contact         |
| cricketers_data |
| employee        |
| tutorials       |
+-----------------+
4 rows in set (0.00 sec)

使用 python 刪除表

您可以根據需要隨時使用 MYSQL 的 DROP 語句刪除表,但在刪除任何現有表時必須非常小心,因為刪除表後資料將無法恢復。

要使用 python 從 MYSQL 資料庫中刪除表,請在遊標物件上呼叫execute()方法,並將 drop 語句作為引數傳遞給它。

示例

下表從資料庫中刪除了一個名為 EMPLOYEE 的表。

import mysql.connector

#establishing the connection conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb'
)

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

#Retrieving the list of tables print("List of tables in the database: ") 
   cursor.execute("SHOW Tables") print(cursor.fetchall())

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

#Retrieving the list of tables print(
   "List of tables after dropping the EMPLOYEE table: ") 
   cursor.execute("SHOW Tables") print(cursor.fetchall())

#Closing the connection conn.close()

輸出

List of tables in the database:
[('employee',), ('employeedata',), ('sample',), ('tutorials',)]
Table dropped...
List of tables after dropping the EMPLOYEE table:
[('employeedata',), ('sample',), ('tutorials',)]

僅在存在時刪除表

如果您嘗試刪除資料庫中不存在的表,則會出現以下錯誤:

mysql.connector.errors.ProgrammingError: 1051 (42S02): 
   Unknown table 'mydb.employee'

您可以透過在刪除語句中新增 IF EXISTS 來驗證表是否存在,從而防止此錯誤。

import mysql.connector

#establishing the connection
conn = mysql.connector.connect(
   user='root', password='password', host='127.0.0.1', database='mydb')

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

#Retrieving the list of tables
print("List of tables in the database: ")
cursor.execute("SHOW Tables")
print(cursor.fetchall())

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

#Retrieving the list of tables
print("List of tables after dropping the EMPLOYEE table: ")
cursor.execute("SHOW Tables")
print(cursor.fetchall())

#Closing the connection
conn.close()

輸出

List of tables in the database:
[('employeedata',), ('sample',), ('tutorials',)]
Table dropped...
List of tables after dropping the EMPLOYEE table:
[('employeedata',), ('sample',),
('tutorials',)]
廣告