Loading...

Python PostgreSQL

Python PostgreSQL Drop Table

 

Delete a Table

You can delete an existing table by using the "DROP TABLE" statement:

FILE: drop_table.py

import psycopg2
conn = psycopg2.connect(database = "kwikl3arn", user = "postgres", password = "post123", host = "localhost", port = "5432")
conn.autocommit = True
print ("Opened database successfully")

cur = conn.cursor()

cur.execute('DROP TABLE customers')

print ("table deleted successfully")
conn.close()

RUN:

C:\Users\Your Name>python drop_table.py

Opened database successfully
table deleted successfully

Drop Only if Exist

If the the table you want to delete is already deleted, or for any other reason does not exist, you can use the IF EXISTS keyword to avoid getting an error.

 FILE: drop_table2.py

import psycopg2
conn = psycopg2.connect(database = "kwikl3arn", user = "postgres", password = "post123", host = "localhost", port = "5432")
conn.autocommit = True
print ("Opened database successfully")

cur = conn.cursor()

cur.execute('DROP TABLE IF EXISTS customers')

print ("table deleted successfully")
conn.close()

RUN:

C:\Users\Your Name>python drop_table2.py

Opened database successfully
table deleted successfully