How to update the data to SQL Server using Python pyodbc?

Today lesson is how we will update 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. Update one record to 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()
# update data to table
sql = "UPDATE dbo.test SET Column3 = 'test4' WHERE Column1 = test1'"
cursor.execute(sql) 
cursor.commit()
print(cursor.rowcount, "record(s) affected")
# 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 *