How to update a Azure SQL table using python

897456 106 Reputation points
2023-04-12T12:59:50.5933333+00:00

Hello Experts, I have a requirement to query and update a column in an Azure SQL db using Python. If I use the pyodb I am getting an error. Pandas only support SQLAlChemy.
I tried using SQLAlchemy , but no luck. Please let me know if you have a working example to update some records using python

import pyodbc
server = '<server>.database.windows.net'
database = '<database>'
username = '<username>'
password = '{<password>}'   
driver= '{ODBC Driver 17 for SQL Server}'

with pyodbc.connect('DRIVER='+driver+';SERVER=tcp:'+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password) as conn:
    with conn.cursor() as cursor:
        cursor.execute("SELECT TOP 3 name, collation_name FROM sys.databases")
        row = cursor.fetchone()
        while row:
            print (str(row[0]) + " " + str(row[1]))
            row = cursor.fetchone()
Azure SQL Database
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Alberto Morillo 34,671 Reputation points MVP Volunteer Moderator
    2023-04-12T17:35:33.9666667+00:00

    Using SQLAlchemy, here you will find how to perform an Update statement?
    Below an example using PYODBC:

    import pyodbc
    server = 'mysql1000.database.windows.net'
    database = 'DemoDatabase'
    username = 'azureadmin'
    password = 'Test@123' 
    driver= '{ODBC Driver 17 for SQL Server}'
    
    with pyodbc.connect('DRIVER='+driver+';SERVER=tcp:'+server+';PORT=1433;DATABASE='+database+';UID='+username+';PWD='+ password) as conn:
        with conn.cursor() as cursor:
            cursor.execute("UPDATE [dbo].[Student] SET Stream = 'Electrical' WHERE [Student ID] = 1607")
    
    

    Here you will find a full CRUD example using PYODBC.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.