I am trying to connect to SQL Server in our domain network. I am able to connect using python but not able to connect in Node.js using Tedious.
Node.js code snippet:
var config = {
server: 'serverName.domain.com',
authentication: {
type: 'default',
options: {
userName: 'DOMAINID\\username',
password: 'password'
}
},
options: {
database: 'dbName',
port: 1234,
}
};
var connection = new Connection(config);
connection.on('connect', function (err) {
if (err) {
console.log('err', err);
} else {
console.log("Connected");
executeStatement();
}
});
connection.connect();
Receiving error:
Login Failed for the user DOMAINID/username. The login is from an untrusted domain and cannot be used with Windows authentication.
But when trying to connect from Python, I am able to connect successfully.
Python snippet:
import sqlalchemy
conn = sqlalchemy.create_engine('mssql+pymssql://DOMAINID\\username:password#serverName.domain.com:1234/dbName')
print(conn.execute('SELECT * FROM table_name').fetchall())
Data received successfully in python.
And also I tried with mssql and msnodesqlv8 with Microsoft ODBC 11 for Microsoft SQL Server drivers.
I am able to connect. Following is the code snippet.
const sql = require("mssql/msnodesqlv8");
const main = async () => {
const pool = new sql.ConnectionPool({
server: "server.domain.com",
database: "dbName",
port: 1234,
user:'DomainId\\username', // Working without username and password
password:'password',
options: {
trustedConnection: true // working only with true
}
});
await pool.connect();
const request = new sql.Request(pool);
const query = 'select * from table';
const result = await request.query(query);
console.dir(result);
};
main();
In the above snippet, I am able to connect without username and password but with trustedConnection true only. I am using windows authentication not SQL authentication. How can I connect using tedious js
Related
I am able to retrieve data from Microsoft Azure SQL Database using below code: -
const sql = require("mssql");
var config = {
user: "user_name",
password: "Pass#1234",
server: "mydb.database.windows.net",
database: "db_name",
options: {
enableArithAbort: true,
},
stream: true,
};
module.exports = function getQueryResult(query) {
return new Promise((res, rej) => {
sql.connect(config).then((pool) => {
pool.query(query, (err, result) => {
if (err) rej(err);
res(result);
});
});
});
};
I am using getQueryResult function to get the data from database.
Everything is going perfect accept the thing that the below errors occurs in between.
Failed to connect to mydb.database.windows.net:1433 in 15000ms (Microsoft Azure SQL Database)
ConnectionError: Failed to connect to mydb.database.windows.net:1433 read ECONNRESET
ConnectionError: Failed to connect to mydb.database.windows.net:1433 socket hang up
I know this question has been asked before. But I have tried all the solutions. None of the solution was specifically for Microsoft Azure SQL Database so I thought might be there is some problem in database.
Thanks in advance.
Your code is a bit different from mine, my options is enclosed in double quotes. You also can download my sample code, it works for me, I have test it.
Tips:
You need set the rule of Firewalls. Make sure your local or webapp can access dbserver.
My code:
const sql = require('mssql')
const config = {
user: 'username',
password: 'pwd',
server: '***sqlserver.database.windows.net', // You can use 'localhost\\instance' to connect to named instance
database: 'yourdb',
"options": {
"encrypt": true,
"enableArithAbort": true
}
}
const poolPromise = new sql.ConnectionPool(config)
.connect()
.then(pool => {
console.log('Connected to MSSQL')
return pool
})
.catch(err => console.log('Database Connection Failed! Bad Config: ', err))
module.exports = {
sql, poolPromise
}
I'm developing VS Code extension and want to get some data from SQL Server database. I've tried many different examples but non of them are working for me.
const Connection = require('tedious').Connection;
const config = {
user: 'ssrs', // tried userName, username
password: 'ssrs',
server: 'localhost',
options: {
database: 'imdb'
}
}
const connection = new Connection(config);
connection.on('connect', function(err: string) {
if (err) {
console.log(err);
} else {
console.log('Connected');
}
});
OR
await sql.connect('mssql://ssrs:ssrs#localhost/imdb')
const result = await sql.query`select 1 as one`
console.dir(result)
OR
const sql = require("mssql");
const conn = new sql.ConnectionPool({
database: "imdb",
server: "localhost",
driver: "msnodesqlv8",
userName: "ssrs",
password: "ssrs"
});
conn.connect().then(() => {
console.log('Connected');
});
ConnectionError: Login failed for user ''.
Connecting via sqlcmd:
The port is also open (1433) as I can telnet to it.
Messages from SQL Server log:
Date 2019-05-08 11:19:02 AM Log SQL Server (Current - 2019-05-05
2:53:00 PM)
Source Logon
Message Login failed for user ''. Reason: An attempt to login using
SQL authentication failed. Server is configured for Integrated
authentication only. [CLIENT: 127.0.0.1]
Date 2019-05-08 11:19:02 AM Log SQL Server (Current - 2019-05-05
2:53:00 PM)
Source Logon
Message Error: 18456, Severity: 14, State: 58.
Trying to connect with Powershell:
PS C:\WINDOWS\system32> Invoke-Sqlcmd -query "select CURRENT_USER, USER_NAME()" -ServerInstance "localhost" -username "ssrs" -password "ssrs" -Database 'imdb'
Column1 Column2
------- -------
ssrs ssrs
As shown in your screenshot, you're able to connect via SQLCMD utility. This means there's no issue with the user or the authentication mode in SQL Server.
The error message is however misleading and other users already experienced this here.
I'm no expert of node.js but I'd recommend you to better understand how the mssql plugin and Connection object work. I think that some missing setting in your configuration is making the connection attempt fail.
For example, this code you posted is wrong (userName is not valid):
const sql = require("mssql");
const conn = new sql.ConnectionPool({
database: "imdb",
server: "localhost",
driver: "msnodesqlv8",
userName: "ssrs",
password: "ssrs"
});
conn.connect().then(() => {
console.log('Connected');
});
It should be:
const sql = require("mssql");
const conn = new sql.ConnectionPool({
database: "imdb",
server: "localhost",
driver: "msnodesqlv8",
user: "ssrs",
password: "ssrs"
});
conn.connect().then(() => {
console.log('Connected');
});
The reason you can't connect is written in the log:
Reason: An attempt to login using SQL authentication failed. Server is
configured for Integrated authentication only.
You have to change the authentication mode (which you already did according to the screenshot posted) and restart the SQL Server service with Agent. Did you restart the service after changing the mode?
I am trying to connect to sql server from node.js like so -
const sql = require('mssql')
const pool = new sql.ConnectionPool({
database: 'db',
server: 'name',
port: 41041,
driver: 'msnodesqlv8',
options: {
trustedConnection: true,
integratedSecurity: true
}
})
pool.connect().then(() => {
//simple query
pool.request().query('select top 10 * from sync', (err, result) => {
console.dir(result)
})
})
But it is giving me this error - ConnectionError: Failed to connect to name:41041 in 15000ms at Connection.tedious.once.err
I am successfully able to connect via ssms like so name, 41041. Maybe it is unable to connect because it is using name: 41041. Any ideas on how to fix this?
I've a node application which do have a connection to SQL Server.
Also, I'm using database as a service from Azure.
Code Snippet :
import { Connection } from 'tedious';
import { Request } from 'tedious';
var config = {
userName: 'dbuser',
password: 'dbpassword',
server: 'mydatabase.database.windows.net',
options: {
instanceName: 'SQLEXPRESS', // Removed this line while deploying it on server as it has no instance.
database: 'dbname'
}
};
connection = new Connection(config);
connection.on('connect', function(err) {
if (err) {
console.log('error : '+err);
} else {
console.log("Connected to Database");
}
});
It has a successful connection, if done, locally.
Console Output => Connected to Database.
Deep dive done using console log :
-> Connection object is being created, but, the event ".on" is not being able to establish.
-> The connection gets established when deployed locally, while, when deployed on server, it doesn't works.
Based on the documentation here, you need to provide an additional option for encrypted connection.
Please try the following for config:
var config = {
userName: 'dbuser',
password: 'dbpassword',
server: 'mydatabase.database.windows.net',
options: {
database: 'dbname',
encrypt: true //Need to add this for connecting to Azure DB
}
};
Using this configuration, I was able to connect to my database hosted in Azure.
I am developing a Node.js-Express-EJS web application, with Azure SQL DB (cloud version of MS SQL Server).
I try to test my connection first on the remote Azure SQL DB, using SQL Server Management Studio. First, I set my machine's IP to be allowed in Azure SQL DB firewall rules. Then I was able to get into the database, create and populate table, and query using the Management Studio.
Now, I have the Node.js app locally first. However, it seems it can't connect to the remote Azure SQL DB using same credentials.
First, I use the tutorial in node-mssql:
/* Using node-mssql */
var sql = require('mssql');
router.get('/test/mssql', function(req, res, next) {
console.log('Testing node-mssql')
sql.connect("mssql://<username>:<password>#<server>.database.windows.net/<db>")
.then(function() {
new sql.Request()
.query('SELECT * FROM mytable')
.then(function(recordset) {
console.dir(recordset);
}).catch(function(err) {
console.log(err);
});
}).catch(function(err) {
console.log(err);
});
});
I was only able to get from the console
'Testing node-mssql'
GET /contact/test/mssql - - ms - -
But no response, it seems its waiting forever, it didn't even throw error.
Same thing happens when I use Sequelize.js
/* Using Sequelize.js */
var Sequelize = require('sequelize');
var sequelize = new Sequelize('<db>', '<username>', '<password>', {
host: '<mydb>.database.windows.net',
dialect: 'mssql',
pool: {
max: 5,
min: 0,
idle: 10000
},
});
router.get('/test/sequelize', function(req, res, next) {
console.log('Testing sequelize');
sequelize.authenticate()
.then(function(err) {
console.log('Connection has been established successfully');
})
.catch(function(err) {
console.log('Unable to connect to the database:', err);
});
});
Result:
Testing sequelize
GET /test/sequelize - - ms - -
Here are the versions that I am using:
Node.js - 4.6.0
express - 4.14.0
mssql - 3.3.0
sequelize - 3.30.2
tedious - 1.14.0
(I wonder if this has to do with me connected on WiFi? But impossible, bec. Management Studio works fine right?)
If you're trying it out with Azure SQL Database, you'd need to add ?encrypt=true to your connection string that will look like:
mssql://<username>:<password>#<server>.database.windows.net/<db>?encrypt=true
For Sequelize.js, you'd need this: dialectOptions: { encrypt: true }. The code will look like:
var sequelize = new Sequelize('<db>', '<username>', '<password>', {
host: '<mydb>.database.windows.net',
dialect: 'mssql',
// Use this if you're on Windows Azure
dialectOptions: {
encrypt: true
},
pool: {
max: 5,
min: 0,
idle: 10000
},
});
I think the issue is with your connection string, as that doesn't look like a SQL Database connection string that would work.
For mssql, try connecting like this:
var config = {
server: "<servername>.database.windows.net",
database: "<dbname>",
user: "<username>",
password: "<password>",
port: 1433,
options: {
encrypt: true
}
};
sql.connect(config).then(function() { ... } )
FYI for reference, SQL Database (at least through .net) expects a connection string like this, so you might have success with a similar connection string directly passed to sql.connect() (though I haven't tried it):
Server=tcp:[serverName].database.windows.net;Database=myDataBase;
User ID=[LoginForDb]#[serverName];Password=myPassword;Trusted_Connection=False;
Encrypt=True;