📜  Python MySQL-删除表

📅  最后修改于: 2020-11-07 08:48:40             🧑  作者: Mango


您可以使用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添加到DELETE语句来防止此错误。

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',)]