Monday, 21 April 2025

Update value in a SQL table using Python

from sqlalchemy import create_engine, text

# Define the connection string
connection_string = "mssql+pyodbc://your_username:your_password@your_server_name/your_database_name?driver=ODBC+Driver+17+for+SQL+Server"

# Create an engine
engine = create_engine(connection_string)

# Connect to the database
with engine.connect() as connection:
    # Define the SQL UPDATE query
    Part_Rev_inactivate = text("""
        UPDATE [Dbo].[PartRevDimension]
        SET PartStatus = 0
        WHERE PartId = :part_id
        AND PartRev = :part_rev
    """)

    # Define the parameters
    part_id = 'your_part_id_value'
    part_rev = 'your_part_rev_value'

    # Execute the query
    connection.execute(Part_Rev_inactivate, {'part_id': part_id, 'part_rev': part_rev})

    # Commit the transaction
    connection.commit()

print("Value updated successfully.")
Explanation:
  • Replace your_server_nameyour_database_nameyour_username, and your_password with your actual SQL Server connection details.
  • Replace your_part_id_value and your_part_rev_value with the actual values for part_id and part_rev.
  • The text function is used to create a SQL text query.
  • The parameters are passed as a dictionary to the execute method.
  • The connection.execute method is used to execute the update statement with the provided parameters.
  • The connection.commit method is used to commit the transaction, making the changes permanent.
  • The with statement ensures that the connection is properly closed after the block of code is executed.

Make sure to handle exceptions and errors in a production environment to ensure the robustness of your code.

No comments:

Post a Comment