Python SQL Server: Deleting Data

Savigo
You organize your data. Now organize your savings.
Set savings goals, track your progress, and stay on course.
Get Savigo for iPhone 

Summary: in this tutorial, you will learn how to delete data from an SQL Server table in Python.

This tutorial begins where the paginating data tutorial left off.

Deleting a row from a table #

Step 1. First, create a delete.py file within the project directory and define the delete_customer() function:

from connect import create_connection

def delete_customer(id: int) -> int:
    # Connect to the SQL Server
    conn = create_connection()
    if conn is None:
        return 0
    
    # Delete the customer    
    with (conn, conn.cursor() as cursor):
        cursor.execute("DELETE FROM Customers WHERE CustomerID = %s", (id,))
        conn.commit()
        return cursor.rowcount

How it works.

First, import the create_connection function from the connect module.

Second, define a function delete_customer that accepts a customer ID and returns the number of rows deleted.

def delete_customer(id: int) -> int:

Third, connect to SQL Server by calling the create_connection() function and return 0 if the connection fails:

conn = create_connection()
if conn is None:
    return 0

Fourth, manage the Connection and Cursor objects using the with statement:

with (conn, conn.cursor() as cursor):

This eliminates the need to close the Cursor and Connection objects manually.

Fifth, execute a DELETE statement with the id parameter:

cursor.execute("DELETE FROM Customers WHERE CustomerID = %s", (id,))

Sixth, delete the data permanently by calling the commit() method of the Connection object:

conn.commit()

Finally, return the number of rows deleted:

return cursor.rowcount

Step 2. Modify the main.py module to use the delete_customer function:

import logging, sys
from delete import delete_customer

# config logging to console
logging.basicConfig(
    stream=sys.stdout, 
    encoding='utf-8', 
    format='%(levelname)s:%(message)s',
    level=logging.DEBUG
)

# Delete customer with id 1
try:
    row_deleted = delete_customer(1)
    logging.info(f'{row_deleted} row(s) deleted.')
except Exception as e:
    logging.error(f"Error fetching customers: {e}")

How it works.

First, import the delete_customer function from the delete module:

from delete import delete_customer

Second, call the delete_customer function to delete the customer with ID 1:

try:
    row_deleted = delete_customer(1)
    logging.info(f'{row_deleted} row(s) deleted.')
except Exception as e:
    logging.error(f"Error fetching customers: {e}")

Step 3. Open your terminal and run the main.py module to delete the customer with ID 1:

python main.py

Output:

INFO:1 row(s) deleted.

The output indicates that one row was deleted.

Download the project source code #

Download the project source code

Summary #

  • Execute the DELETE statement to delete data from a table in Python.

Was this tutorial helpful?