Python MySQL - Drop Table
Você pode remover uma tabela inteira usando o DROP TABLEdeclaração. Você só precisa especificar o nome da tabela que deseja excluir.
Sintaxe
A seguir está a sintaxe da instrução DROP TABLE no MySQL -
DROP TABLE table_name;
Exemplo
Antes de excluir uma tabela, obtenha a lista de tabelas usando a instrução SHOW TABLES da seguinte forma -
mysql> SHOW TABLES;
+-----------------+
| Tables_in_mydb |
+-----------------+
| contact |
| cricketers_data |
| employee |
| sample |
| tutorials |
+-----------------+
5 rows in set (0.00 sec)
A instrução a seguir remove a tabela denominada sample do banco de dados completamente -
mysql> DROP TABLE sample;
Query OK, 0 rows affected (0.29 sec)
Como excluímos a tabela chamada sample do MySQL, se você obtiver a lista de tabelas novamente, não encontrará nela o nome da tabela sample.
mysql> SHOW TABLES;
+-----------------+
| Tables_in_mydb |
+-----------------+
| contact |
| cricketers_data |
| employee |
| tutorials |
+-----------------+
4 rows in set (0.00 sec)
Removendo uma tabela usando Python
Você pode descartar uma tabela sempre que precisar, usando a instrução DROP do MYSQL, mas você precisa ter muito cuidado ao excluir qualquer tabela existente, pois os dados perdidos não serão recuperados após a exclusão de uma tabela.
Para eliminar uma tabela de um banco de dados MYSQL usando python invoque o execute() no objeto cursor e passe a instrução drop como um parâmetro para ele.
Exemplo
A tabela a seguir remove uma tabela chamada EMPLOYEE do banco de dados.
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()
Resultado
List of tables in the database:
[('employee',), ('employeedata',), ('sample',), ('tutorials',)]
Table dropped...
List of tables after dropping the EMPLOYEE table:
[('employeedata',), ('sample',), ('tutorials',)]
Abandone a mesa apenas se existir
Se você tentar eliminar uma tabela que não existe no banco de dados, ocorrerá um erro como -
mysql.connector.errors.ProgrammingError: 1051 (42S02): Unknown table 'mydb.employee'
Você pode evitar esse erro verificando se a tabela existe antes de excluí-la, adicionando IF EXISTS à instrução DELETE.
Example
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()
Output
List of tables in the database:
[('employeedata',), ('sample',), ('tutorials',)]
Table dropped...
List of tables after dropping the EMPLOYEE table:
[('employeedata',), ('sample',),
('tutorials',)]