1

We have a SQL Server DB setup on Azure VM. We are trying to create an Azure Function App with PowerShell timerTrigger that will make an API call and store result of that into our DB.

Able to make the API call via Azure function successfully and read that data, but getting issues while writing into DB.

ERROR Snippet:

ERROR: Exception calling "Open" with "0" argument(s): "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"

CODE Snippet:

# Define connection parameters

$serverName = "XXX"
$databaseName = "XXX"
$userId = "XXX"
$password = "XXX"
$connectionString = "Server=$serverName;Initial Catalog=$databaseName;User Id=$userId;Password=$password;"

# Open the SQL Server connection

$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()

# Define the SQL query to insert data

$query = "TRUNCATE TABLE [dbo].[Table_1]; INSERT INTO [dbo].[Table_1] ([Test]) VALUES ('" + $accessTokenTrimmed + "');"

# Run query

$command = $connection.CreateCommand()
$command.CommandText = $query
$command.ExecuteNonQuery()
$connection.Close()

1 Answer 1

0

Based on your error, I'd check for 2 things

  1. There's a similar question (https://stackoverflow.com/a/45060455/4317508) where it's recommended to use tcp:sqlserver.database.windows.net, 1433 and to add Connection Timeout in your Connection String

$server = " tcp:mymssqlserver.database.windows.net,1433"

$connectionString = "Server=$server;Database=$database;User ID=$adminName;Password=$adminPassword;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"

  1. Check the Firewall Rules of your Azure SQL Server by going to your SQL Server in Azure, Networking, Public Access and at the bottom check the Firewall Rules, you might need to have the Function App IP Address listed Azure SQL Firewall

To capture your Function App Public IP, go to the Function App, then at your right click on JSON View JSON view Function App

In the JSON that is presented, search (CTRL+F) for Outbound, and use those to add to your Azure SQL Outbound Function App Ips

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.