Update data in Azure SQL DB using Python

To update data in an Azure SQL Database using Python, you can use the pyodbc package. Here’s a sample code to update 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()

# Update query
update_query = """
    UPDATE your_table
    SET column1 = ?,
        column2 = ?
    WHERE condition_column = ?
"""

# Update data
data = ("new_value1", "new_value2", "condition_value")
cursor.execute(update_query, data)

# Commit the changes
connection.commit()

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

print("Data updated successfully!")

In the code above, replace 'your_server_name', 'your_database_name', 'your_username', 'your_password', 'your_table', 'column1', 'column2', and 'condition_column' with the actual values corresponding to your Azure SQL Database, table, columns, 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.

An update query is defined with placeholders (?) for the values to be updated.

The data to be updated is provided as a tuple (data) where each element corresponds to a placeholder in the update query.

The cursor.execute() method is used to execute the update query with the provided data.

After updating 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 update 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