How to delete the data from SQL Server using Python pyodbc?

Today lesson is how we will delete the data to MSSQL Server. We are using python (Latest: Python 3.8.2), pyodbc plugin to achieve this. If you are not sure how to install the Python and plugins, check my previous post.

1. Download and install pyodbc library

$ pip install pyodbc

2. Delete one record from the test table:

# importing the pyodbc library
import pyodbc
# connect to MSSQL DB
conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};
                            SERVER=SQLEXPRESS;
                            DATABASE=TEST;
                            UID=sa;
                            PWD=sa;') 
cursor = conn.cursor()
# delete data from table
sql = "Delete from dbo.test WHERE Column1 = test1'"
cursor.execute(sql)
# close DB connection
cursor.close()
conn.close()

That’s it. I hope this will help. ?
Photo: https://www.brandeps.com

Leave a Reply

Your email address will not be published. Required fields are marked *