Update data in SQL DB using Python

To update data in a SQL database using Python, you need to establish a connection to the database and execute an update query. Here’s a sample code to update data in a SQL database using the pyodbc package:

import pyodbc

# Connect to the database
connection = pyodbc.connect(
    "Driver={your_driver};"
    "Server=your_server;"
    "Database=your_database;"
    "UID=your_username;"
    "PWD=your_password;"
)

# 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_driver', 'your_server', 'your_database', 'your_username', 'your_password', 'your_table', 'column1', 'column2', and 'condition_column' with the actual values corresponding to your SQL database, table, columns, and condition.

The code establishes a connection to the SQL database using the pyodbc.connect() method.

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