Reputation: 323
I created config file for database like below:
module.exports.connection = {
sqlserver: {
user: 'user_name',
password: 'password',
server: 'servername\\instancename',
database: 'database_name',
port: 1433,
},
};
I have a simple table in database:
I'm trying get a data from table above like below:
const sql = require('mssql');
const config = require('../config/connection');
sql.connect(config.connection.sqlserver).then((pool) => pool.request().query('select type from dbo.category')).then((result) => {
console.log(result);
}).catch((err) => {
console.log(err);
});
sql.close();
Unfortunately I doesn't see anything in console and I don't have any error so I can't find what's wrong. I tried also:
sql.connect(config.connection.sqlserver).then((pool) => pool.request().query('select type from dbo.category')).catch((err) => {
console.log(err);
}).then((result) => {
console.log(result);
}).catch((err) => {
console.log(err);
});
sql.close();
I used https://www.npmjs.com/package/mssql#promises. I'm trying to do it on my nodeJs server. Any ideas?
Upvotes: 3
Views: 608
Reputation: 323
I resolved my problem. Thanks for Julia Shestakova suggestions. My query function looks like this:
const sql = require('mssql');
const config = require('./config/connection');
module.exports = {
query(query) {
return sql.connect(config.connection.sqlserver).then(() => sql.query(query)).then((result) => {
sql.close();
return result.recordset;
}).catch((err) => console.log(err));
},
};
I'm returning Promise so I can use then
to presentation my data when I'm calling query function on a server.
Upvotes: 1