Python-data-access-python-postgresql-drop-table
提供:Dev Guides
Python PostgreSQL-ドロップテーブル
DROP TABLEステートメントを使用して、PostgreSQLデータベースからテーブルを削除できます。
構文
以下は、PostgreSQLのDROP TABLEステートメントの構文です-
DROP TABLE table_name;
例
次のクエリを使用して、名前がCRICKETERSとEMPLOYEESの2つのテーブルを作成したとします-
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=#
「\ dt」コマンドを使用してテーブルのリストを確認すると、上記で作成したテーブルを次のように表示できます-
postgres=# \dt;
List of relations
Schema | Name | Type | Owner
--------+------------+-------+----------
public | cricketers | table | postgres
public | employee | table | postgres
(2 rows)
postgres=#
次の文は、データベースからEmployeeという名前のテーブルを削除します-
postgres=# DROP table employee;
DROP TABLE
Employeeテーブルを削除したため、テーブルのリストを再度取得すると、その中の1つのテーブルのみを観察できます。
postgres=# \dt;
List of relations
Schema | Name | Type | Owner
--------+------------+-------+----------
public | cricketers | table | postgres
(1 row)
postgres=#
既に削除しているため、再びEmployeeテーブルを削除しようとすると、次のように「テーブルが存在しません」というエラーが表示されます-
postgres=# DROP table employee;
ERROR: table "employee" does not exist
postgres=#
これを解決するには、DELTEステートメントと一緒にIF EXISTS句を使用できます。 これにより、テーブルが存在する場合は削除され、存在しない場合はDLETE操作がスキップされます。
postgres=# DROP table IF EXISTS employee;
NOTICE: table "employee" does not exist, skipping
DROP TABLE
postgres=#
Pythonを使用してテーブル全体を削除する
DROPステートメントを使用して、必要なときにいつでもテーブルを削除できます。 ただし、既存のテーブルを削除するときは、テーブルを削除した後に失われたデータが復元されないため、非常に注意する必要があります。
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()
出力
#Table dropped...