How to Drop a Table in SQL Server using Python

In this short guide, you’ll see how to drop a table in SQL Server using Python. Example is also included for illustration purposes.

Steps to Drop a Table in SQL Server using Python

Step 1: Install the Pyodbc package

The Pyodbc package can be used to connect Python to SQL Server. If you haven’t already done so, you may install the Pyodbc package using this command (under Windows):

pip install pyodbc

You may check the following guide for the complete steps to install a package in Python using PIP.

Step 2: Connect Python to SQL Server

Next, connect Python to SQL Server using this template (if needed, here is a guide that explains how to connect Python to SQL Server):

import pyodbc 
conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=server_name;'
                      'Database=database_name;'
                      'Trusted_Connection=yes;')

cursor = conn.cursor()

Step 3: Drop the Table in SQL Server

In this final step, you’ll see how to drop a table in SQL Server using a simple example.

For illustration purposes, I’ll drop a table called ‘dbo.People‘ from SQL Server:

How to Drop a Table in SQL Server using Python

Where:

  • The server name is: RON\SQLEXPRESS
  • The database name is: TestDB
  • The table name (with a dbo schema) is: dbo.People

Here is the complete Python code to drop the table (note that you’ll need to modify the code below to reflect your server, database and table information):

import pyodbc 
conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=RON\SQLEXPRESS;'
                      'Database=TestDB;'
                      'Trusted_Connection=yes;')

cursor = conn.cursor()

cursor.execute('DROP TABLE TestDB.dbo.People')
conn.commit()

After you run the code in Python, select your database in SQL Server (e.g., TestDB), and then click on the refresh button. Your table should no longer exist:

Drop a Table in SQL Server using Python