I’ve written a Python script that connects to SQL Server housed in a Virtual Machine hosted in our Azure Environment.
I’ve been able to successfully connect and run the query locally within the Virtual Machine but when I deploy to Azure Functions I’m getting the following error:
(‘01000’, "[01000] [unixODBC][Driver Manager]Can’t open lib ‘ODBC Driver 17 for SQL Server’ : file not found (0) (SQLDriverConnect)")
I successfully ran the script and connected to the database a few days ago, but for some reason, it stopped working and this error now appears.
import pyodbc
DatabaseServer = 'Server'
DatabaseName = 'databasename'
conn_str = "Driver={ODBC Driver 17 for SQL Server };Server="+str(DatabaseServer)+';Database='+str(DatabaseName)+";'Trusted_Connection=yes;"
try:
# Connect to the SQL Server
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
# Execute the query
cursor.execute("SELECT TOP 10 hmy FROM Table")
# Fetch and print the results
rows = cursor.fetchall()
results_str = ""
for row in rows:
results_str += str(row) + "n"
# Close the cursor and connection
cursor.close()
conn.close()
print("Connection to SQL Server Succesful")
except pyodbc.Error as e:
print(f"Error connecting to SQL Server {str(e)}")
Pyodbc is included in the requirements.txt file which is deployed to Azure Functions.
If somebody could help that would be great.
I believe it could be something to do with Azure functions not having the correct ODBC library but I’ve read that it is pre-installed so this shouldn’t be a problem.
2
Answers
Azure Functions Python will have PYODBC module installed by default. Make sure to add pyodbc in requirements.txt.
I used the below code to connect and query Select statement with Azure SQL using Azure Functions and it worked successfully, Refer below:-
My init.py:-
requirements.txt:-
local.settings.json:-
I deployed the above function code in my Azure Function app created with Runtime set to Python 3.10 and Linux OS like below:-
Commands to deploy the Function:-
Added connectionstring setting in the configuration as settings from local.settings.json is not added in the Function app while deployment.
Make sure you check the Function Outbound Ip’s and whitelist these Ip’s in your SQL as mentioned in this SO thread answer.
One alternative is to deploy your Function app in a dedicated plan, Either Premium plan or App Service plan and then run the commands from this Document to install ODBC Driver manually in your Function app.
Commands:-
Checked the OS version that was Debian and than ran the script from the document specific to Debian.
This happened to me when I deployed a python 3.11 azure function using azure functions core tools:
func azure functionapp publish <name_of_azure_function>
. When I switched back to python 3.10, the ODBC Driver 17 for SQL Server driver was installed. Support for Python 3.11 in azure functions is in public preview: https://azure.microsoft.com/en-us/updates/public-preview-support-for-python-311-in-azure-functions/