Comments (5)
My problem is that whenever the code reaches connection.connect()
from the second time on, it will hit the error EALREADYCONNECTING
, because the connection is still being opened.
I thought about doing some sort of Promise pool of queries to be resolved once connect itself get resolved via a Promise, but right now my brain is very confused!
let mssql = require('mssql');
let fs = require('fs');
class Database
{
static connect(username, password, server, database)
{
if (Database.connection !== null) {
return Database.connection;
}
let storedUsername = null;
let storedPassword = null;
let storedServer = null;
let storedDatabase = null;
try {
fs.accessSync(__dirname + '/../../config.json');
let data = fs.readFileSync(__dirname + '/../../config.json')
data = JSON.parse(data);
storedUsername = data.sql.username;
storedPassword = data.sql.password;
storedServer = data.sql.server;
storedDatabase = data.sql.database;
} catch (e) {
// Do nothing
}
var config = {
user: username || storedUsername || '',
password: password || storedPassword || '',
server: server || storedServer || 'localhost',
database: database || storedDatabase || '',
}
Database.connection = new mssql.Connection(config);
return Database.connection;
}
static getConnection()
{
if (Database.connection === null) {
try {
Database.connect();
} catch (e) {
throw new Error('Database.getConnection: Database not connected.');
}
}
return Database.connection;
}
static getInstance()
{
return mssql;
}
static query(query, fields)
{
if (typeof query !== 'string' || typeof fields !== 'object') {
throw new Error("Invalid parameters");
}
let db = Database.getInstance();
let connection = Database.getConnection();
let ps = new db.PreparedStatement(connection);
let values = {};
fields.forEach(function(current, index) {
ps.input(current.name, current.type);
values[current.name] = current.value;
});
connection.connect(function(err) {
if (err) {
throw err;
}
ps.prepare(query, function(err) {
if (err) {
throw new Error(err);
}
ps.execute(values, function(err, recordset, affected) {
if (err) {
ps.unprepare(function(err) {
if (err) {
throw new Error(err);
}
});
throw new Error(err);
}
ps.unprepare(function(err) {
if (err) {
throw new Error(err);
}
});
});
});
});
}
}
Database.connection = null;
module.exports = Database;
from node-mssql.
Best practice is to open one sql.Connection
and share it (or use global connection way). Once you execute a query, a new TCP connection is acquired from the pool internally. Once the query is complete, connection is released back to the pool automatically. You don't have to close anything. Maximum number of internal concurrent connections is configurable (see docs). Idle TCP connection are closed automatically after some time (also configurable).
from node-mssql.
Closing due to inactivity.
from node-mssql.
Sorry to comment on such an old issue but I'm banging my head against this library. Incidentally I tried to setup a singleton intermediary class that would start the start the connection and then share that connection via static methods. My problem is that I'm having difficulties to setup things so that the connection is already open when it's time to run queries, but without having to reopen it again. Since the opening of the connection is of course async, I cannot just put everything in the opening callback, because that happens totally somewhere else at another time... the only thing I can do is to share sql.Connection, which is "connecting".
How can I open the connection and move on to prepare statements and run queries knowing that the connection is open?
from node-mssql.
For reference: http://stackoverflow.com/q/41686882/1092853
from node-mssql.
Related Issues (20)
- Dynamic Where query not working HOT 3
- SQL Query Error: 'Invalid usage of the option NEXT in the FETCH statement' with Paginated Fetch Query HOT 1
- mssql 6 incompatible with node v12 HOT 1
- IN clause parametrize issue HOT 1
- How to connect to SQL Server using tedious (Windows Authentication) HOT 1
- Issue connecting to MSSQL DB in Linux environment HOT 3
- How to use the user-defined data types?
- you have a typo in your readme sql.query`some query` HOT 1
- ConnectionError: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified HOT 1
- Potential impact of disabling connection validation when released from the pool HOT 1
- RequestError: Incorrect syntax near '='. Unable to query to table when values containing equal sign '=', HOT 7
- The "config.server" property is required and must be of type string. HOT 1
- @azure/core-rest-pipeline breaking support for node.js 14 HOT 2
- Does node-mssql support multiSubnetFailover? HOT 9
- Suspected memory leak when streaming data HOT 4
- arrayRowMode returns a function for the column type HOT 6
- Problem with Persian/Arabic characters when using input() HOT 4
- Testing library-using code in Jest results in SyntaxError: Unexpected token 'export' HOT 1
- Request timeouts in mssql/msnodesqlv8 when using default Pool size HOT 4
- Bulk Insert row lock not supported HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from node-mssql.