I have a question here. I want to set up a Google sheet and populate this sheet with numbers from my local database. And my network is VPN network. I program in Google spreadsheet script editor. Using the following code to connect my local database:
var address = '10.0.0.71:1433/DatabaseName';
var username = 'DOMAIN\username';
var password = 'root';
var dbUrl = 'jdbc:sqlserver://' + address;
function createDatabase() {
var conn = Jdbc.getConnection(dbUrl, username, password);
var stmt = conn.createStatement();
var rs = stmt.execute('SELECT * FROM ITEM');
stmt.close();
conn.close();
}
However, this connection test doesn't work at all.
The error is:
Failed to establish a database connection. Check connection string, username and password.
From my understanding of Google Apps Scripts, your database need to be reachable from the Internet (that's how Google works, in the Cloud).
Related
I'm using .NET 6, Azure Function version 4 and SqlClient in my Azure Function application.
I have a connection string like this
Server=tcp:name.database.windows.net,1433;Initial Catalog=dbName;Persist Security Info=False;User ID=username;Password=password;MultipleActiveResultSets=True;Encrypt=True;TrustServerCertificate=False;Connection Timeout=120;
Normally, I access this database using GlobalProtect by providing it portal, username and password.
Now, I'm developing an Azure Function app which will access this database, but I'm getting this error
System.Private.CoreLib: Exception while executing function:
MyAzurefunction. Core .Net SqlClient Data Provider: Cannot open
server 'serverName' requested by the login. Client with IP address
'MyIpAddress' is not allowed to access the server. To enable
access, use the Windows Azure Management Portal or run
sp_set_firewall_rule on the master database to create a firewall rule
for this IP address or address range. It may take up to five minutes
for this change to take effect.
I know I'm getting this error because my IP Address doesn't have access to the server but how can I connect to it via my Connection String?
I create azure SQL database. connection string of database:
Server=tcp:<serverName>.database.windows.net,1433;Initial Catalog=<database Name>;Persist Security Info=False;User ID=server;Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
Image for reference:
I created function app with .net 6 in visual studio.
Image for reference:
I published it to Azure.
Image for reference:
Selected the ellipse(...) on the published page and selected Manage Azure App Service settings.
Image for reference:
Click on Add Setting in Application page and add the name of setting.
Image for reference:
In sql_connection enter the connection string of sql db in Local section for remote section click on Insert Value from Local.
Image for reference:
Install System.Data.SqlClient package in Manage Nuget packages of project. I added below code that connects to SQL Database :
using System.Data.SqlClient;
using System.Threading.Tasks;
[FunctionName("DatabaseCleanup")]
public static async Task Run([TimerTrigger("*/15 * * * * *")]TimerInfo myTimer, ILogger log)
{
// Get the connection string from app settings and use it to create a connection.
var str = Environment.GetEnvironmentVariable("sqldb_connection");
using (SqlConnection conn = new SqlConnection(str))
{
conn.Open();
var text = "UPDATE SalesLT.SalesOrderHeader " +
"SET [Status] = 5 WHERE ShipDate < GetDate();";
using (SqlCommand cmd = new SqlCommand(text, conn))
{
// Execute the command and log the # rows affected.
var rows = await cmd.ExecuteNonQueryAsync();
log.LogInformation($"{rows} rows were updated");
}
}
}
Above function runs every 15 seconds to update the Status column based on the ship date.
I added my IP address in database firewall settings.
Image for reference:
At 15 seconds after startup, the function runs.
Output of number of rows updated in the SalesOrderHeader table:
In this way I connected to my SQL database to my function app.
I want to query an Azure SQL Database from an Azure Function executing on my machine in debug using Managed Identities (i.e. the identity of my user connected to Visual Studio instead of providing UserId and Password in my connection string).
I followed this tutorial on Microsoft documentation so my Azure SQL Server has an AD user as admin which allowed me to give rights (db_datareader) to an Azure AD group I created with my Azure Function Identity and my user in it (and also my Function App deployed in Azure).
If I deploy and run in Azure my Azure Function, it is able to query my database and everything is working fine. But when I run my Azure Function locally, I have the following error :
Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'.
The code of my function is the following:
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "test")] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
using (var connection = new SqlConnection(Environment.GetEnvironmentVariable("sqlConnectionString")))
{
connection.AccessToken = await (new AzureServiceTokenProvider()).GetAccessTokenAsync("https://database.windows.net");
log.LogInformation($"Access token : {connection.AccessToken}");
try
{
await connection.OpenAsync();
var rows = await connection.QueryAsync<Test>("select top 10 * from TestTable");
return new OkObjectResult(rows);
}
catch (Exception e)
{
throw e;
}
}
}
The code retrieves a token correctly, the error occurs on line await connection.OpenAsync().
If I open the database in Azure Data Studio with the same user than the one connected to Visual Studio (which is member of the AD group with the rights on the database), I can connect and query the database without any issue.
Is it a known issue or am I missing something here ?
After trying your specific scenario, I tested quite a few ways to try and get it to work locally. This didn't work, giving the same error message you're getting.
I discussed it with some people, when a possible solution came up. I tested it: it works!
The main issue in my case was that my subscription (and my user) is a Microsoft account (Outlook). Because of this, you need to specify the tenantId in the GetAccessTokenAsync() call.
Apparently, for managed identities you do not have to specify the tenantId. With a user, it's a good idea to explicitly specify it. In case of a personal MS account, specifying it is mandatory.
My code (sort of):
var tokenProvider = new AzureServiceTokenProvider();
using (var connection = new SqlConnection(CONNECTIONSTRING))
using (var command = new SqlCommand(QUERY, connection))
{
connection.AccessToken = await tokenProvider.GetAccessTokenAsync("https://database.windows.net/", "<YOUR_TENANT_ID>");
await connection.OpenAsync();
var result = (await command.ExecuteScalarAsync()).ToString();
return new OkObjectResult(result);
}
This solution has been tested and works both when specifying the tenantId (or Directory ID, the tenant's GUID) and the 'onmicrosoft'-name (xxx.onmicrosoft.com).
Is your local machine's IP Address white-listed?
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-firewall-configure
I need to query an on-premises SQL Server Express database from my Azure app service based on Nodejs. I followed this tutorial to add a hybrid connection.
I successfully connected and added this connection to my service. I also added the connection string as:
Server=LOCALHOST\\SQLEXPRESS,1433;Database=smartpointmovil_db;User ID=sa;Password=pass1009
Then, I wrote an easy api in node JS for my azure mobile app service:
"get": function (req, res, next) {
var sql = require("mssql");
var config = {
server: 'LOCALHOST\\SQLEXPRESS',
user: 'sa',
password: 'pass1009',
database: 'smartpointmovil_db',
port: 1433
};
var conn = new sql.Connection(config);
var req=new sql.Request(conn);
conn.connect(function(err){
if(err){
console.log("Error connectig: "+err);
return;
}
req.query('select * from smartpointmovil.cat_cadenas where id=1',function(err,results){
if(err){
console.log("Error during query: "+err);
return;
}
else{
console.log("Success: "+results[0].cadena);
res.json(results[0]);
}
conn.close();
});
});
}
Every time I call this API, I get the following error message:
Error connectig: ConnectionError: Failed to connect to
LOCALHOST:undefined in 15000ms
I did not find the way to define in my code the connection string to be used for the query, so I am including the configuration parameters.
Any idea how to write a node js code to query my local database from an Azure hosted service?
Use the hostname (Computer Name) of your on-prem server when defining the Hybrid Connection. Then use the same name to reference that machine in your App Service code.
e.g.
Server=SQL-SRV-01\SQLEXPRESS,1433; [...]
Hybrid Connections work by hooking the getaddrinfo system call, and it's probably unable to tell apart your LOCALHOST from the actual LOCALHOST (127.0.0.1) of the VM that App Service runs on top of.
Test with sqlcmd.exe from the Kudu Console:
D:\home>sqlcmd -S tcp:SQL-SRV-01,1433 -U {username} -P {password}
-Q "SELECT NAME FROM sys.sysdatabases"
NAME
-------------------
master
MobileServiceZZZ_db
(2 rows affected)
I got it working, these are the changes I did in my code to make it work:
Changed from server name from 'LOCALHOST' to my server host name: 'quandojhv' which is the same name used as host name in the hybrid connection.
I removed the instance name '\SQLEXPRESS' in the server configuration parameter.
New configuration parameters in my code are:
var config = {
server: 'quandojhv',
user: 'sa',
password: 'pass1009',
database: 'smartpointmovil_db',
options: {
encrypt: true
}};
I am trying to create a connection to an oracle db instance (oracle:thin) using Airflow.
According to their documentation I entered my hostname followed by port number and SID:
Host: example.com:1524/sid
filled other fields as:
Conn Type: Oracle
Schema: username ( documentation says: use your username for schema )
Login: username
Password: * * *
After connection is setup, it gives the save error code for every query that I tried to execute (ORA-12514).
It seems like oracle doesn't let airflow to connect:
ORA-12514: TNS:listener does not currently know of service requested in connect descriptor
Has someone experienced the same problem before. I mean connecting to a database shouldn't be a problem for a big platform like this. Or I am probably doing something wrong. Thanks
Version: Airflow v1.7.0, Oracle11g
EDIT:
I am using the same hostname which I use in Oracle SQLDeveloper client:
After digging into the source code, this is what finally how it worked for me:
Conn Type: Oracle
Host: example.com
schema: username
login: username
port: port number
extra: {"sid": "my sid", "dsn": "example.com"}
You have a problem in your connection settings, either your setting is not loading properly to the oracle hook or you are missing a python package that save/load your connection settings. You can test it by hard coding your credentials.
https://github.com/airbnb/airflow/blob/master/airflow/hooks/oracle_hook.py
conn = self.get_connection(self.oracle_conn_id)
dsn = conn.extra_dejson.get('dsn', None)
sid = conn.extra_dejson.get('sid', None)
service_name = conn.extra_dejson.get('service_name', None)
if dsn and sid and not service_name:
dsn = cx_Oracle.makedsn(dsn, conn.port, sid)
conn = cx_Oracle.connect(conn.login, conn.password, dsn=dsn)
elif dsn and service_name and not sid:
dsn = cx_Oracle.makedsn(dsn, conn.port, service_name=service_name)
conn = cx_Oracle.connect(conn.login, conn.password, dsn=dsn)
else:
conn = cx_Oracle.connect(conn.login, conn.password, conn.host)
for service name usage, if you leave (port, schema and extra) empty, you can put the full oracle connection descriptor under Host:
(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)) (CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = mysidname)))
this worked for me in extra field
{ "dsn":"192.168.x.x" , "service_name":"some.service.name" }
I get from https://github.com/apache/airflow/blob/master/airflow/hooks/oracle_hook.py#L49
If anyone just does not see the connection in the Ad hoc query dropdown - you need to install the adapter: pip install cx_Oracle on the airflow server.
Connection string to connect the SQLSERVER Express Database and How to take setup of that database with my application.....
The following snippet should get you started .
SQLConnectionStringBuilder bldr = new SQLConnectionStringBuilder
bldr.DataSource = "Server" //Put your server or server\instance name here. Likely YourComputerName\SQLExpress
bldr.InitialCatalog = "MyDB" //The database on the server that you want to connect to.
bldr.UserID = "SomeUser" //The user id
bldr.Password = "SomePassword" //The pwd for said user account
SQLConnection myConnection = new SQLConnection(bldr.ConnectionString)