Link to home
Start Free TrialLog in
Avatar of Eric Malysa
Eric Malysa

asked on

How do you connect and query a remote MS SQL Server with Nodejs?

Hello, I am looking for simple code that shows how to connect to a MS SQL Server using nodejs. Everything I have found is overly complicated.
I want code that shows how to connect to the server. It's remote.
Also run a simple query. Querying one row.

The code below is what we were using to just connect to a local Access Database.
I need it modified to connect to MS SQL Server.
Thanks.

describe('test db connection', function () {
  it('tests db connection', function () {      
                var ADODB = require('node-adodb');
                var connection = ADODB.open('Provider=Microsoft.ACE.OLEDB.12.0;Data Source=CDPDB.accdb;');
                connection
                  .query("Select @@Version")
                  .then(data => {
                                console.log(JSON.stringify(data, null, 2));
                  })
                  .catch(error => {
                                console.error(error);
                  });
   browser.sleep(5000);
});
});
Avatar of noci
noci

Maybe using: https://www.npmjs.com/package/mssql

This is the driver for MSSQL fron NodeJS.
SQL Server connection strings may vary and the syntax depends on the driver used.

You may try the following modification of the connection string:
var connection = ADODB.open('Driver={SQL Server Native Client 11.0};Server=myServerIPAddress\ServerName;Trusted_Connection=yes;');

If the trusted login does not work then try to provide user and pwd.

More info: https://www.connectionstrings.com/sql-server/
Avatar of Eric Malysa

ASKER

This put me on the right path. Thanks.  I have to wait till I have the server ip address. What I don't understand is why I could connect to the database through SQL Server Management Studio with just the server name.
You can use the ServerName (Windows Server name) + SQL Server instance name in the connection string. Your application just needs to know how to translate the server name to IP address. You may obtain the IP yourself by e.g. PING command.
It looks like I have to wait until I can get the permissions needed in order to access the DB through automation. Hopefully this week. I will update this thread with which solution worked. Thanks.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.