I created this Microsoft SQL Server and a database with two tables in it. I am using Node.js for the backend but I am having trouble making a connection from node.js to mssql. I am using Visual Studio and have all the required frameworks and packages needed. I am not getting any errors but I'm also not getting the output. I want to understand if its connected and I want the code to work. My node.js and SQL are working fine though.
const sql = require('mssql')
const sqlConfig = {
server: "10.0.0.102\\MSSQLSERVER",
port: 1433,
pool: {
max: 10,
min: 0,
idleTimeoutMillis: 30000
},
options: {
encrypt: true,
trustServerCertificate: false
}
}
async () => {
try {
// make sure that any items are correctly URL encoded in the connection string
await sql.connect(sqlConfig)
const result = await sql.query`select * from multiuserlogin`
console.dir(result)
} catch (err) {
// ... error checks
}
}
Related
i'm having some trouble connecting node to the database, it keeps throwing me an error of ssl and i tried a lot of different videos and stuff to see if it works but nothing does, here is what i'm currently doing
import sql from 'mssql'
const dbSettings = {
user: 'admin',
password: 'system',
server: 'localhost',
database: 'master',
options: {
trustedConnection: true,
encrypt: true,
trustServerCertificate: true,
},
}
async function getConnection() {
const pool = sql.connect(dbSettings)
const result = await sql.query("SELECT 1")
console.log(result)
}
getConnection()
i also tried this as well but didn't work either
async function getConnection() {
const pool = await sql.connect(dbSettings)
const result = await pool.request().query("SELECT 1")
console.log(result)
i also checked if the SQL Server authentication is enabled with windows and SQL Server and it is, i can log in into SQL Server with that info, but somehow is having trouble creating the connection, by the way, this is the error message it is showing me:
node_modules\mssql\lib\tedious\connection-pool.js:70
err = new ConnectionError(err)
^
ConnectionError: Failed to connect to localhost:1433 - 186B0000:error:0A000102:SSL routines:ssl_choose_client_version:unsupported protocol:c:\ws\deps\openssl\openssl\ssl\statem\statem_lib.c:1986
any tips or solution you can give me to solve this problem would be really helpful to me, thank you very much in advance.
EDIT
I noticed that the connection error only appears when i call the function getConnection if i remove it it doesn't appear, however i need to make sure that the connection was properly established and see the response from the database to move on
change encrypt: true to encrypt: false
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
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 running a small website that connects to MongoDB Atlas. It has a replicaset with 3 members. For the most part, everything works just fine, but every now an then Atlas' replicaset crashes (or something?) and Mongoose stops working from then on. It throws a single error - MongoError: no primary found in replicaset and that's it.
It doesn't fire mongoose.connection.on('error'), and no errors are reported after this point. It just fails to return any data.
It's sort of hard for me to debug this, as this is running in production, and I have no way of telling when replicaset will fail. Here's how I connect:
function connect() {
tries++;
mongoose.Promise = Promise;
const { uri, options } = config.mongoDb;
return mongoose.connect(uri, options);
}
let db = connect();
db
.connection
.on('error', (err) => {
Raven.captureException(err);
db.disconnect();
})
.on('disconnected', () => {
db = connect();
});
And my options look like this:
options: {
server: {
autoReconnect: true,
ssl: true,
poolSize: 10,
socket_option: {
keepAlive: true
}
}
}
Has anyone had similar problems before? Any idea what I'm doing wrong here, or how to actually catch the error, so I can properly reconnect?
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;