- Python SQLite - Discussion
- Python SQLite - Useful Resources
- Python SQLite - Quick Guide
- Python SQLite - Cursor Object
- Python SQLite - Join
- Python SQLite - Limit
- Python SQLite - Drop Table
- Python SQLite - Delete Data
- Python SQLite - Update Table
- Python SQLite - Order By
- Python SQLite - Where Clause
- Python SQLite - Select Data
- Python SQLite - Insert Data
- Python SQLite - Create Table
- Python SQLite - Establishing Connection
- Python SQLite - Introduction
- Python SQLite - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Python SQLite - Drop Table
You can remove an entire table using the DROP TABLE statement. You just need to specify the name of the table you need to delete.
Syntax
Following is the syntax of the DROP TABLE statement in PostgreSQL −
DROP TABLE table_name;
Example
Assume we have created two tables with name CRICKETERS and EMPLOYEES using the following queries −
sqpte> CREATE TABLE CRICKETERS ( First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, Place_Of_Birth VARCHAR(255), Country VARCHAR(255) ); sqpte> CREATE TABLE EMPLOYEE( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT ); sqpte>
Now if you verify the pst of tables using the .tables command, you can see the above created tables in it (pst) as −
sqpte> .tables CRICKETERS EMPLOYEE sqpte>
Following statement deletes the table named Employee from the database −
sqpte> DROP table employee; sqpte>
Since you have deleted the Employee table, if you retrieve the pst of tables again, you can observe only one table in it.
sqpte> .tables CRICKETERS sqpte>
If you try to delete the Employee table again, since you have already deleted it you will get an error saying “no such table” as shown below −
sqpte> DROP table employee; Error: no such table: employee sqpte>
To resolve this, you can use the IF EXISTS clause along with the DELETE statement. This removes the table if it exists else skips the DELETE operation.
sqpte> DROP table IF EXISTS employee; sqpte>
Dropping a Table Using Python
You can drop a table whenever you need to, using the DROP statement of MYSQL, but you need to be very careful while deleting any existing table because the data lost will not be recovered after deleting a table.
Example
To drop a table from a SQLite3 database using python invoke the execute() method on the cursor object and pass the drop statement as a parameter to it.
import sqpte3 #Connecting to sqpte conn = sqpte3.connect( example.db ) #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()
Output
Table dropped...Advertisements