Failed to connect to local SQL Server using node - sql-server

I am trying to connect to a local SQL Server database using the following config:
var config = {
server: "localhost",
port:1433,
user: 'sa',
password: 'sa',
database: 'newarbete',
options: {
trustedconnection:true,
}
}
but I failed. I get this error
Failed to connect to localhost:1433 - Could not connect (sequence)
I can connect to the same db when it is on the server (changing the config parameters of course).
What is wrong with the config parameters for the local database, or what I should do to make work here?

Related

Knex cannot connect to LocalDB instance using named pipe

I'm attempting to connect to a LocalDB instance through Knex using a named pipe:
np:\\.\pipe\LOCALDB#DBFBFA07\tsql\query
I can connect to it perfectly fine through SSMS & sqlcmd, but whenever I set my Knex config.server property to the named pipe, it says Failed to connect to: np:\\...\query - getaddrinfo ENOTFOUND np:\\...\query
The dev config that I'm using:
development: {
client: "mssql",
connection: {
database: process.env.SQLSERVER_DB,
user: process.env.SQLSERVER_USER,
password: process.env.SQLSERVER_PASSWORD,
server: process.env.SQLSERVER_SERVER
}
}
and my .env config:
SQLSERVER_DB=<db_name>
SQLSERVER_USER=<username>
SQLSERVER_PASSWORD=<password>
SQLSERVER_SERVER="np:\\.\pipe\LOCALDB#DBFBFA07\tsql\query"
The underlying mssql driver and TDS protocol implementation does not support named pipe connections to LocalDB. See this

NodeJS OracleDB connection string

I am running Oracle XE 21c in a Docker container and I can connect to it with a JDBC thin connection using the JDBC url jdbc:oracle:thin:#localhost:1521:XE using the SYSTEM account. I can also log into the terminal Docker instance and connect to the database fine.
When I try to connect to it using NodeJS OracleDB example code described here:
https://node-oracledb.readthedocs.io/en/latest/user_guide/connection_handling.html, I cannot get the client to connect using either:
connection = await oracledb.getConnection({
user : "hr",
password : mypw
connectString : "localhost/XEPDB1"
});
or
connection = await oracledb.getConnection({
user : "SYSTEM",
password : "MyPassword",
connectString : "localhost/XE"
});
I get an error ORA-01017: invalid username/password; logon denied.
I can connect to Oracle XE using sqlplus either by logging into the Docker container or from the host Mac using:
sqlplus SYSTEM/Password#localhost:1521/XE
if I change the nodejs code to:
const connection = await oracledb.getConnection({
//user: "SYSTEM",
//password: "Password42",
//connectString: connectionURI.url
connectString: "SYSTEM/Password#localhost:1521/XE"
});
I get the error:
ORA-12154: TNS:could not resolve the connect identifier specified
Any ideas why I can connect with sqlplus but not NodeJS OracleDB?

Node.js Connection with SQL Server windows authentication

I'm trying to connect node.js to mssql in Windows Authentication mode. I installed the tedious,mssql and msnodesqlv8 modules, but I still can't figure out how to open a connection.
This is what I tried:
var sql = require('mssql');
var config = {
driver: 'msnodesqlv8',
server: 'POPPY-GI\\SQLEXPRESS',
database: 'NodinSports',
options:{
trustedConnection: true,
useUTC: true}}
sql.connect(config).then(function() {
new sql.Request().query('select * from users')
.then(function(recordset){
console.log(recordset);
}).catch(function(err) {
console.log(err);});
}).catch(function(err) {
console.log(err);});
After running I get a long error saying:
`ConnectionError`: Port for `SQLEXPRESS` not found in
`ServerName`;POPPYGI;`InstanceName;SQLEXPRESS;IsClustered`;No;Version;12.0.2000.8;;
at Connection.tedious.once.err (D:\Never Lazy\University\`AN2, SEM 2\WEB\`Projek`\node_modules\`mssql`\lib\`tedious.js:216:17`)
at Connection.g (events.js:291:16)
at emitOne (events.js:96:13)
at Connection.emit (events.js:188:7)
at D:\Never Lazy\University\AN2,SEM2\WEB\Projekt\node_modules\tedious\lib\connection.js:570:27
at D:\Never Lazy\University\AN2,SEM2\WEB\Projekt\node_modules\tedious\lib\instance-lookup.js:91:24
at Socket.onMessage (D:\Never Lazy\University\AN2,SEM2\WEB\Projekt\node_modules\tedious\lib\sender.js:140:9)
at emitTwo (events.js:106:13)
at Socket.emit (events.js:191:7)
at UDP.onMessage (dgram.js:549:8)
code: 'EINSTLOOKUP',
I would be really thankful for any help.
FIXED:
In services.msc check if the followings are enabled:
SQL Server(*server_name*) -- in my case `SQLEXPRESS`
SQL Server Browser
SQL Server Agent(*server_name*) -- if you are using `SQLEXPRESS` this doesn't need to run
In SQL Server Configuration Manager -> Protocols for server_name: enable TCP/IP.
To make sure everything will be fine, check the port the server is using (SQL Server Configuration Manager -> SQL Native Client Configuration -> Client Protocols -> double click on TCP/IP -> Default Port ) , and add the port: *your_port* to the code in var config = { ... }.
Lastly, change var sql = require('mssql'); to var sql = require("mssql/msnodesqlv8");
Install the following modules:
"dependencies": {
"msnodesqlv8": "^0.4.14",
"mssql": "^4.1.0"
}
My node version: v8.1.4
const sql = require("mssql/msnodesqlv8");
const main = async () => {
const pool = new sql.ConnectionPool({
server: "myservername",
database: "mydbname",
options: {
trustedConnection: true
}
});
await pool.connect();
const request = new sql.Request(pool);
const query = `SELECT [FirstName]
,[LastName]
,[Email]
FROM [Dev].[Users]`;
const result = await request.query(query);
console.dir(result);
};
main();
(You can do it without async or older versions: https://stackoverflow.com/a/40406998/639575)
The solution given by beatoss works for windows but not for Linux/mac. The msnodesqlv8 driver only works for Windows. For Linux/mac environment, try odbc instead.
It may be too late to answer, but this recently happened with me and it drove me crazy!!! I was trying to connect my db to express and I was working with windows authentication mode. For two long days I kept googling and refreshing until I got this article: https://www.liquidweb.com/kb/troubleshooting-microsoft-sql-server-error-18456-login-failed-user/
So in a nutshell;
First I installed the msnodesqlv8 driver for windows authentication, then in the my server on ssms, I right clicked on my server then in properties and then security, I enabled sql server and windows authentication mode, then in the object explorer, clicked on the plus next to the server, then security, then logins. There I saw sa with a cross next to it. In it's properties, I changed my password to something easier to remember (optional), then in the status, set the login to enable. PHEW!
Now my config code: <br / >
const config = {
user: 'sa',
password: '123',
driver: "msnodesqlv8",
server: 'UZAIR-S_PC\\SQLEXPRESS',
database: 'LearningExpressJS',
options: {
trustedconnection: true,
enableArithAbort : true,
trustServerCertificate: true,
instancename : 'SQLEXPRESS'
},
port: 58018
}
This works finally !!!!!!!!!!!!!!!

Config entry in node.js in case if of windows authentication to connect to SQL Server

How to create config entry in Node.Js to connect to SQL Server in the case of Windows Authentication using only mssql module?
I'm using this approach:
exports.dbConfig = {
server: "AKASH",
database: "SampleDB",
port: 1433,
options: {
trustedConnection: true
}
};

Node.js MSSQL tedius ConnectionError: Failed to connect to localhost:1433 - connect ECONNREFUSED

I am trying to connect to MSSQL 2012 using NodeJS with the mssql connection interface.
When attempting to connect I get the following error:
{ [ConnectionError: Failed to connect to localhost:1433 - connect ECONNREFUSED]
name: 'ConnectionError',
message: 'Failed to conncet to localhost:1433 - connect ECONNREFUSED',
code: 'ESOCKET' }
Any ideas on how to fix this?
The solution is to enable TCP connections which are disabled by default.
My case wasn't exactly the same as Matt's, but his screenshot was enough to remember me what was missing.
As it is said here, when you are using the SQL Server Instance Name to connect to it, you must have SQL Server Browser running.
options.instanceName
The instance name to connect to. The SQL Server
Browser service must be running on the database server, and UDP port
1434 on the database server must be reachable.
(no default)
Mutually exclusive with options.port.
If after enabling the TCP connection and your configuration is still not working. Here's my own-configuration.
var config = {
"user": 'admin',
"password": 'password',
"server": 'WINDOWS-PC',
"database": 'database_name',
"port": 61427, // make sure to change port
"dialect": "mssql",
"dialectOptions": {
"instanceName": "SQLEXPRESS"
}
};
If somebody still struggles to connect despite doing all that was proposed.
In my case I had to manually set TCP Port property to 1433 in SQL Server Network Configuration -> Protocols for ... -> TCP/IP -> IP Addresses -> IPAll.
[
Best practice is to first verify the connection to the SQL server using a query analyzer (SQL Management Studio (Windows) or SQLPro for MSSQL (Mac)) using the same protocol, port and credentials as you wish to use via your application.
In Management Studio, the format is Server,Port (e.g. 192.168.1.10,1433); and you'll probably be using SQL Server Authentication instead of Windows Authentication.
Steps to configure the SQL Server:
Install with Mixed Authentication, if you intend to use SQL Server Authentication.
Setup SQL Server to listen on TCP on a fixed port number:
SQL Configuration Manager SQL Server Network Configuration
Protocols for {Instance}
TCP/IP - Enabled
(double-click)
IP Address (on all desired interfaces)
TCP Dynamic Ports = BLANK! (not zero)
TCP Port - 1433 (or desired port)
In my case there was a configuration issue.This was the wrong configuration
let config = {
server: 'localhost',
authentication: {
type: 'default',
options: {
userName: 'sa', // update me
password: 'xxxxx' // update me
}
},
options: {
database: 'SampleDB',
validateBulkLoadParameters:false,
}}
Then I have added encrypt variable to the options.It solved my issue.Corrected configuration
let config = {
server: 'localhost',
authentication: {
type: 'default',
options: {
userName: 'sa', // update me
password: 'xxxxxx' // update me
}
},
options: {
database: 'SampleDB',
validateBulkLoadParameters:false,
encrypt: false,
}
}
**Please follow the connection configuration and little test:**
//Declare global variable
var http = require('http');
var events = require('events');
var nodemailer = require('nodemailer');
var sql = require('mssql');<br/>
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;
//Create an http server
http.createServer(function(req,res)
{
res.writeHead(200, {'Content-Type': 'text/html'});
var Connection = require('tedious').Connection;
//Configure the connection
var config = {
userName: '<user id>',
password: '<password>',
server: '<system ip>',
options: {database: '<database name>'}
};
var connection = new Connection(config);
connection.on('connect', function(err) {
console.log("Connected");
executeStatement();
});
function executeStatement() {
request = new Request("select getdate();", function(err) {
if (err) {
console.log(err);}
});
var result = "";
request.on('row', function(columns) {
columns.forEach(function(column) {
if (column.value === null) {
console.log('NULL');
} else {
result+= column.value + " ";
}
});
console.log(result);
result ="";
});
connection.execSql(request);
};
return res.end();
}).listen(8080);
//Post configuration test on browser:
http://localhost:8080/
Apart from setting TCP port no to 1433.
If you are getting "Connection lost - Cannot call write after a stream was destroyed" error
This error will also come if you use options.encrypt: true on Node v12+ with old SQL Server versions.
This is caused by Node v12 requiring TLS 1.2.
install the TLS 1.2 security patch for your SQL Server
run node with backwards compatibility flag:
node --tls-min-v1.0
eg: node --tls-min-v1.0 app.js
disable encrypted communication by setting
options.encrypt: false (optional)
Config Object:
const config = {
user: '...',
password: '...',
server: 'localhost',
database: '...',
'options.encrypt': false
}
Ref: https://github.com/tediousjs/tedious/issues/903#issuecomment-614597523
I couldn't connect with 'localhost' although I use 'localhost' in SQL Management Studio and other applications.
When I used Computer Name (network address), it worked!
My issue was that I needed to start sqlserver using docker first on my mac using this command
sudo docker start sqlserver
For me changing this condition from 'No' to 'Yes' worked:
switch (key) {
case 'instance':
return this.config.options.instanceName
case 'trusted':
return this.config.options.trustedConnection ? 'Yes' : 'Yes'
It just doesn't load the value from the options object even if I provide it.
I hardcoded this change in file \node_modules\mssql\lib\msnodesqlv8\connection-pool.js

Resources