Delete data in Azure SQL DB using Python

To delete data from an Azure SQL Database using Python, you can utilize the pyodbc package. Here’s a sample code to delete data in Azure SQL Database:

 
import pyodbc

# Connect to the database
server = 'your_server_name.database.windows.net'
database = 'your_database_name'
username = 'your_username'
password = 'your_password'
driver = '{ODBC Driver 17 for SQL Server}'
conn_str = f"DRIVER={driver};SERVER={server};DATABASE={database};UID={username};PWD={password}"
connection = pyodbc.connect(conn_str)

# Create a cursor
cursor = connection.cursor()

# Delete query
delete_query = """
    DELETE FROM your_table
    WHERE condition_column = ?
"""

# Delete data
condition_value = "value_to_delete"
cursor.execute(delete_query, condition_value)

# Commit the changes
connection.commit()

# Close the cursor and the connection
cursor.close()
connection.close()

print("Data deleted successfully!")

In the code above, replace 'your_server_name', 'your_database_name', 'your_username', 'your_password', 'your_table', and 'condition_column' with the actual values corresponding to your Azure SQL Database, table, and condition.

The code establishes a connection to the Azure SQL Database using the pyodbc.connect() method. You need to provide the server name, database name, username, password, and the appropriate driver for your SQL Server version.

A delete query is defined with a placeholder (?) for the condition value.

The condition value is provided as an argument to the cursor.execute() method.

After deleting the data, the changes are committed using connection.commit().

Finally, the cursor and the connection are closed, and a success message is printed to the console.

Make sure to have the pyodbc package installed. You can install it using pip:

pip install pyodbc

Remember to handle any exceptions that may occur during the database connection or delete operation for proper error handling.

Pamai Tech
Turning ideas into Reality

Products

Office Add-in

Enterprise Solutions

Cloud Consulting

UI UX Design

Data Transformation

Services

FAQ's

Privacy Policy

Terms & Condition

Team

Contact Us

Company

About Us

Services

Features

Our Pricing

Latest News

© 2023 Pamai Tech