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:

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, let’s drop a table called “dbo.product” from SQL Server.

Where:

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

Here is the complete Python code to drop the table for our example (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=test_database;"
    "Trusted_Connection=yes;"
)

cursor = conn.cursor()

cursor.execute("DROP TABLE test_database.dbo.product")
conn.commit()

After you run the code in Python, your table should no longer exist.

You may also want to check the following guide for the steps to create a table in SQL Server using Python.

Leave a Comment