从NodeJs连接SQL数据库 – ConnectionError:连接尚未打开

我试图从NodeJs连接SQL数据库,但得到此错误: 查询数据库时出错: – ConnectionError:连接尚未打开。

var executeQuery = function(res, query){ var conn = new sql.ConnectionPool(dbConfig); conn.connect().then(function () { // create Request object var request = new sql.Request(conn); // query to the database request.query(query, function (err, queryResult) { if (err) { console.log("Error while querying database :- " + err); res.send(err); } else { res.send(queryResult); } }); conn.close(); }); } 

请帮忙。

谢谢你,詹姆斯

连接池类将返回一个承诺,该承诺通过您的连接启动的池来解决:

  var executeQuery = function(res, query) { var conn = new sql.ConnectionPool(dbConfig); conn.connect() .then(function (pool) { // ^ the pool that is created and should be used // create Request object var request = new sql.Request(pool); // ^ the pool from the promise // query to the database request.query(query, function (err, queryResult) { if (err) { console.log("Error while querying database :- " + err); res.send(err); } else { res.send(queryResult); } }); conn.close(); }); } 

在你的情况下, connvariables始终是承诺,而不是连接本身。

文档中连接池的基本示例如下所示:

 new sql.ConnectionPool(config).connect().then(pool => { return pool.query`select * from mytable where id = ${value}` }).then(result => { console.dir(result) }).catch(err => { // ... error checks })