我在用node.js连接mssql,用的node-mssql,用下面方法进行封装,单条测试没有问题,但是进行连续插入时,只有最后一个能够正常插入,错误提示:Connection is closed. 查了半天,发现这种写法是官方文档上写的Quick Example with one global connection,这样是只建立了一个全局连接,前面没有操作完成,就被后面的连接打断了,所以出错?但此库的连接配置中又提供了pool的配置!我错在哪里,该如何做呢?谢谢!
var mssql = require('mssql');
var options = {
server: config.server,
port: config.port,
user: config.user,
password: config.password,
database: config.database,
pool: {
max: 10,
min: 2,
idleTimeoutMillis: 30000
}
}
...
function query(sql,params){
return new Promise(function(fulfill, reject) {
mssql.connect(options, function(err) {
console.dir(arguments)
if(err){
reject({err:err.message})
logger.error(err.message)
}else{
let sqlReq = new mssql.Request();
if(params){
let ps = Object.keys(params);
for(let i = 0; i < ps.length; i++){
sqlReq.input(ps[i],params[ps[i]])
}
}
sqlReq.query(sql, function(error, result) {
if (error) {
reject({err:error.message});
logger.error(error.message + ' Sql is : ' + sql)
} else {
fulfill(result);
logger.debug(sql)
}
});
}
});
});
迷茫2017-04-17 14:01:00
It has been solved. The documentation on node-mssql is incomplete. Read the official documentation carefully. There is a return parameter in new sql.Connection. This parameter is used as the new sql.request() parameter, and that’s it!
var connection = new sql.Connection(config, function(err) {
// ... error checks
var request = new sql.Request(connection); // or: var request = connection.request();
request.query('select 1 as number', function(err, recordset) {
// ... error checks
console.dir(recordset);
});
});
Document address: http://csdoc.org/
Why are the documents inconsistent? It’s really a rip off. I spent an entire afternoon!