SQL Server how to use SQL update query in azure functions SQL output binding in python

nwsw7zdq  于 2023-08-02  发布在  Python
关注(0)|答案(1)|浏览(114)

I just started working with Azure functions in Python and I'm very new to this. The goal of my app is to run a complicated model and write the results to a new column in an existing connected Azure SQL database. Each result corresponds to a unique case listed in the 'MyID' column, and should be added to the correct row.

My database table columns look something like this:

MyID,  A,   B,   C

My code calculates the values that need to be written in column 'C'.

I successfully connected the Azure SQL database to azure functions and I'm able to read in all data from a database table using the azure input SQL binding in a function.json file.

I was also able to write new rows to the existing table using the azure SQL output binding.

However, I cannot figure out how I can write data to a specific column of a specified row in this way. An ordinary SQL query of what I would like to do would look something like this:

"UPDATE dbo.MyTable SET C = result_C WHERE MyID = result_myID"

Here, result_C is the result calculated by my model and result_myID is the the case which the results corresponds to.

A normal binding in my function.json looks like this:

{
      "name": "results",
      "type": "sql",
      "direction": "out",
      "commandText": "dbo.MyTable",
      "connectionStringSetting": "SqlConnectionString"
    }

And in all other examples I could find, only the table name is specified in the output binding. So how to use the update query? Something like:

{
      "name": "results",
      "type": "sql",
      "direction": "out",
      "commandText": "update dbo.MyTable set [C] where [MyID] = result_myID",
      "commandType": "Text",
      "connectionStringSetting": "SqlConnectionString"
    }

This unsurprisingly does not work. First and foremost since I don't now how to pass the current value of "result_myID" to the function.json. Also I'm not sure if i can use "commandText" in this way for an output binding.

So should the query take place in the python file instead? Normally it looks like:

import azure.functions as func

def main(additional_input, results: func.Out[func.SqlRow]):

         \\calculations->outcome\\

         results.set(func.SqlRowList(outcome))
         
         return()

Unfortunately I have no idea how or where to implement that sql update query statement in the code above.

Is it even possible to use the functions SQL connections for this? Or should I just use the pyodbc python package in my python file to manually connect to the database and not bother with the bindings?

Any help or pointers would be greatly appreciated!

ulmd4ohb

ulmd4ohb1#

In order to run UPDATE statement in azure SQL via Azure Python Function, You can make use of Pyodbc module with ODBC Driver for SQL Server [Driver version 17 or 18] installed in your local system.

You can install ODBC Driver 17 for SQL server from this link

My init.py:-

import logging
from multiprocessing import connection
import pyodbc
import os
import azure.functions as func

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    
    connectionstring = os.environ["connectionstring"]
    conn = pyodbc.connect(connectionstring)
    cursor = conn.cursor()
  
    cursor.execute("UPDATE OnlineCourses SET Title = 'Azure-9001' , Topic = 'Azure12' where CourseID = 1")
    conn.commit()
    
    conn.commit()
    cursor.close()
    conn.close()

        
    # Prepare & Return the HTTP Response
    return func.HttpResponse(
                body="Your request is processed",
                status_code=202
        )

My local.settings.json containing connection string to my Azure SQL:-

You can find the connection string of Azure SQL from Connection String section like below:-

Make sure your connection string is in the same format as I have mentioned below with your SQL server host name, database name and username and password:-

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=valleystrg54;AccountKey=xxxxxxq+AStHLzSmA==;EndpointSuffix=core.windows.net",
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "connectionstring" : "DRIVER={ODBC Driver 17 for SQL Server};SERVER=tcp:siliconserver.database.windows.net;PORT=1433;DATABASE=silicondb;UID=username;PWD=Password"
  }
}

Function.json:-

Azure SQL row got updated, Refer below:-

相关问题