connect()
returns a promise, so you need to chain a .then()
to wait for the connection
const fs = require('fs');
const os = require('os');
const mssql = require('mssql');
class Database {
/**
* Ottieni il riferimento alla libreria di riferimento
*
* @static
* @returns
*
* @memberof Database
*/
static getLib() {
return mssql;
}
/**
* Apri connessione al database usando le configurazioni impostate.
*
* @private
* @static
* @param {string} [username]
* @param {string} [password]
* @param {string} [server]
* @param {string} [database]
* @returns
*
* @memberof Database
*/
static openConnection(username, password, server, database) {
if (Object.prototype.hasOwnProperty.call(this, 'connectionPromise') === true && this.connectionPromise !== null) {
return this.connectionPromise;
}
const configuration = this.getConfiguration(username, password, server, database);
if (!this.enable) {
return Promise.reject('Database disabled.');
}
this.connectionPool = new mssql.ConnectionPool(configuration);
this.connectionPromise = this.connectionPool.connect();
return this.connectionPromise;
}
static closeConnection() {
this.connectionPool.close();
}
/**
* Promessa alla connessione del database, che verrà avviata non appena viene richiesta la prima volta.
*
* @public
* @static
* @returns {Promise} <ConnectionPool>
*
* @memberof Database
*/
static willConnect() {
if (Object.prototype.hasOwnProperty.call(this, 'connectionPromise') === false || this.connectionPromise === null) {
try {
return this.openConnection();
} catch (err) {
console.error('willConnect: Database not connected.');
throw new Error(err);
}
}
return this.connectionPromise;
}
static getConnectionPool() {
return this.connectionPool;
}
/**
* Ottieni l'oggetto di configurazione per la connessione al database.
*
* @private
* @static
* @param {string} [username]
* @param {string} [password]
* @param {string} [server]
* @param {string} [database]
* @memberof Database
*/
static getConfiguration(username, password, server, database) {
let storedUsername = null;
let storedPassword = null;
let storedServer = null;
let storedDatabase = null;
let storedTimeout = null;
try {
fs.accessSync(`${__dirname}/../../config.js`);
const config = require(`${__dirname}/../../config`);
this.enable = config[this.configKey] ? config[this.configKey].enable : this.enable;
storedUsername = config[this.configKey] ? config[this.configKey].username : null;
storedPassword = config[this.configKey] ? config[this.configKey].password : null;
storedServer = config[this.configKey] ? config[this.configKey].server : null;
storedDatabase = config[this.configKey] ? config[this.configKey].database : null;
storedTimeout = config[this.configKey] ? config[this.configKey].timeout : null;
} catch (err) {
console.warn(err);
}
return {
user: storedUsername || username || '',
password: storedPassword || password || '',
server: storedServer || server || 'localhost',
database: storedDatabase || database || '',
connectionTimeout: storedTimeout || '15000',
requestTimeout: storedTimeout || '15000',
options: {
appName: os.hostname(),
},
};
}
/**
* Metodo generalista per lanciare query
*
* @public
* @static
* @param {string} query
* @param {array} [fields]
* @returns {Promise}
*
* @memberof Database
*/
static query(query, fields) {
const validQuery = typeof query === 'string';
const validFields = typeof fields === 'object' || typeof fields === 'undefined';
if (!validQuery || !validFields) {
throw new Error('Invalid parameters');
}
// il parametro fields è opzionale
const fieldsArray = fields || [];
const connection = this.willConnect();
if (!this.enable) {
return Promise.reject('Database disabled');
}
const db = this.getLib();
const ps = new db.PreparedStatement(this.connectionPool);
const values = {};
fieldsArray.forEach((current) => {
ps.input(current.name, current.type);
values[current.name] = current.value;
});
let results = null;
return connection.then(() => {
return ps.prepare(query)
.then(() => {
results = ps.execute(values);
return results;
}, (reason) => {
console.warn(reason);
})
.then(() => ps.unprepare(), () => ps.unprepare())
.then(() => results)
.catch((reason) => {
console.warn(reason);
});
});
}
}
Database.configKey = '';
Database.pool = null;
Database.connection = null;
module.exports = Database;
const pool = new sql.ConnectionPool(config, (err) => {
if (err) {
console.error('DB Error callback:', err.message)
throw new Error(err)
}
})
I have this error callback in my connection pool. I changed my config so the connection doesn't actually log in so I can test the error handling. Why am I still getting these "UnhandledPromiseRejections"[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node index.js`
Server is listening on 8080
DB Error callback: Login failed for user 'sas'.
(node:2732) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: ConnectionError: Login failed for user 'sas'.
(node:2732) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.(node:2732) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): ConnectionError: Login failed for user 'sas'.
Greetings! Does node-mssql support auto-incrementing id's during bulk upload? I have attempted multiple column configurations such as , table.columns.add('id', sql.Int, { primary: true identity: true });
- however I still require to input values for these columns which is not the desired effect.
To expand, TSQL's CREATE TABLE mytable ([id] INT IDENTITY(1,1) NOT NULL)
will auto increment on each insert of a new row. Thoughts/suggestions?
table.rows.add()
with the values for each column in order.
const sqlInstance = require('mssql');
const express = require('express');
const app = express();
app.get('/', (req, res) => {
if (req.query.p == 'sql') {
var setUp = {
server: 'myservername',
database: 'Products',
user: 'Products',
password: 'Products',
port: 1433,
options: {
encrypt: true
}
};
sqlInstance.connect(setUp).then(function (connection) {
var _sqlRequest = new sqlInstance.Request(connection)
.query("[GetAllProducts]")
.then(function (dbData) {
if (dbData == null || dbData.length === 0)
res.send('No data boss!');
res.send('Loaded big data');
sqlInstance.close();
})
.catch(function (error) {
console.dir(error);
});
})
} else {
res.send('Responded to static request!!!');
}
})
var printLog = function(log){ console.log(log);};
app.listen(3000, () => console.log('Example app listening on port 3000!'))
hi im trying to dynamically add tvp data into tvp table. I need some help here…
I have already new
the table and added the columns no problem there
let columns = _.map(tvpData.columns, 'name');
tvpData.data.forEach((item) => {
tvp.rows.add.apply(null, columns.map((c) => item[c]));
});
but it seems stuck in this foreach. any help would be appreciated
host
be the name of the database or a URL?var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect((err) => {
if (err) {
console.error(`error connecting: ${err.stack}`);
return;
}
console.log(`connected as id ${connection.threadId}`);
});
connection.end();
host
to my DB host nameConnection {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
config:
ConnectionConfig {
host: '...',
port: 3306,
localAddress: undefined,
socketPath: undefined,
user: '...',
password: '...',
database: '...',
connectTimeout: 10000,
insecureAuth: false,
supportBigNumbers: false,
bigNumberStrings: false,
dateStrings: false,
debug: undefined,
trace: true,
stringifyObjects: false,
timezone: 'local',
flags: '',
queryFormat: undefined,
pool: undefined,
ssl: false,
multipleStatements: false,
typeCast: true,
maxPacketSize: 0,
charsetNumber: 33,
clientFlags: 455631 },
_socket: undefined,
_protocol:
Protocol {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
readable: true,
writable: true,
_config:
ConnectionConfig {
host: '...',
port: 3306,
localAddress: undefined,
socketPath: undefined,
user: '...',
password: '...',
database: '...',
connectTimeout: 10000,
insecureAuth: false,
supportBigNumbers: false,
bigNumberStrings: false,
dateStrings: false,
debug: undefined,
trace: true,
stringifyObjects: false,
timezone: 'local',
flags: '',
queryFormat: undefined,
pool: undefined,
ssl: false,
multipleStatements: false,
typeCast: true,
maxPacketSize: 0,
charsetNumber: 33,
clientFlags: 455631 },
_connection: [Circular],
_callback: null,
_fatalError: null,
_quitSequence: null,
_handshake: false,
_handshaked: false,
_ended: false,
_destroyed: false,
_queue: [],
_handshakeInitializationPacket: null,
_parser:
Parser {
_supportBigNumbers: false,
_buffer: <Buffer >,
_nextBuffers: [Object],
_longPacketBuffers: [Object],
_offset: 0,
_packetEnd: null,
_packetHeader: null,
_packetOffset: null,
_onError: [Function: bound handleParserError],
_onPacket: [Function: bound ],
_nextPacketNumber: 0,
_encoding: 'utf-8',
_paused: false } },
_connectCalled: false,
state: 'disconnected',
threadId: null }
Hi folks,
Does anyone have any experience with using SESSION_CONTEXT
on SqlServer 2016/2017?
I'm running into some issues, and I'm hoping someone can help me confirm it's not just me!
// Assuming some connection pool: cp
const sql = require('mssq');
const request = new sql.Request(cp).query("SELECT SESSION_CONTEXT(N'user_var') AS [sc]");
request
.then(r => console.log(r))
.catch(e => console.log(e));
I'm running into an internal error
, with an unknown
sqlstate
. I'm hoping I'm missing something here. Any ideas?
Cheers!
dhensby on master
Update changelog for v5 Merge pull request #796 from dh… (compare)