Python PostgreSQL - Drop Table
Puoi eliminare una tabella dal database PostgreSQL utilizzando l'istruzione DROP TABLE.
Sintassi
Di seguito è riportata la sintassi dell'istruzione DROP TABLE in PostgreSQL:
DROP TABLE table_name;
Esempio
Supponiamo di aver creato due tabelle con il nome CRICKETERS e EMPLOYEES utilizzando le seguenti query:
postgres=# CREATE TABLE CRICKETERS (
First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int,
Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);
CREATE TABLE
postgres=#
postgres=# CREATE TABLE EMPLOYEE(
FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20),
AGE INT, SEX CHAR(1), INCOME FLOAT
);
CREATE TABLE
postgres=#
Ora se verifichi l'elenco delle tabelle utilizzando il comando "\ dt", puoi vedere le tabelle create sopra come -
postgres=# \dt;
List of relations
Schema | Name | Type | Owner
--------+------------+-------+----------
public | cricketers | table | postgres
public | employee | table | postgres
(2 rows)
postgres=#
La seguente istruzione elimina la tabella denominata Employee dal database:
postgres=# DROP table employee;
DROP TABLE
Poiché hai eliminato la tabella Employee, se recuperi nuovamente l'elenco di tabelle, puoi osservare solo una tabella al suo interno.
postgres=# \dt;
List of relations
Schema | Name | Type | Owner
--------+------------+-------+----------
public | cricketers | table | postgres
(1 row)
postgres=#
Se provi a eliminare di nuovo la tabella Employee, poiché l'hai già eliminata, riceverai un errore che dice "la tabella non esiste" come mostrato di seguito -
postgres=# DROP table employee;
ERROR: table "employee" does not exist
postgres=#
Per risolvere questo problema, è possibile utilizzare la clausola IF EXISTS insieme all'istruzione DELTE. Ciò rimuove la tabella se esiste altrimenti salta l'operazione DLETE.
postgres=# DROP table IF EXISTS employee;
NOTICE: table "employee" does not exist, skipping
DROP TABLE
postgres=#
Rimozione di un'intera tabella utilizzando Python
È possibile eliminare una tabella ogni volta che è necessario, utilizzando l'istruzione DROP. Ma è necessario fare molta attenzione durante l'eliminazione di una tabella esistente perché i dati persi non verranno recuperati dopo aver eliminato una tabella.
import psycopg2
#establishing the connection
conn = psycopg2.connect(database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432')
#Setting auto commit false
conn.autocommit = True
#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()
Produzione
#Table dropped...