Course Content
Python Indentation, Comments and Variables
0/2
Object Oriented Programming in Python
0/1
Exception Handling in Python
0/1
Sending emails with Python
0/1
Unit test in python programming
0/1
Python programming (zero to advance!!!)
About Lesson

Python SQLite – DROP Table

To drop a table in SQLite using Python, you can execute an SQL `DROP TABLE` statement using the cursor’s `execute()` method. Here’s how you can do it:

1. Establish Connection: Begin by establishing a connection to the SQLite database file using the `connect()` function from the `sqlite3` module.

2. Create Cursor: After establishing the connection, create a cursor object using the `cursor()` method.

3. Execute SQL Statement: Use the cursor’s `execute()` method to execute an SQL `DROP TABLE` statement to remove the desired table from the database.

4. Commit Changes: After executing the `DROP TABLE` statement, you need to commit the changes to the database using the `commit()` method of the connection object.

5. Close Cursor and Connection: Finally, close the cursor and connection using the `close()` method to release any resources associated with them.

Here’s an example demonstrating how to drop a table named `employees`:

“`python
import sqlite3

# Establish connection to SQLite database
connection = sqlite3.connect(‘example.db’)

# Create a cursor object
cursor = connection.cursor()

# Execute SQL statement to drop table
cursor.execute(”’
DROP TABLE IF EXISTS employees
”’)

# Commit changes
connection.commit()

# Close cursor and connection
cursor.close()
connection.close()
“`

In this example:

– We establish a connection to an SQLite database file named `example.db`.
– We create a cursor object using the `cursor()` method.
– We execute an SQL `DROP TABLE` statement that removes the `employees` table from the database if it exists.
– We commit the changes to the database using the `commit()` method of the connection object.
– Finally, we close the cursor and connection.

 

Join the conversation