NodeJS和SQL Server连接错误
我正在使用NodeJS连接SQL Server。 我最初的代码是:
const poolA = new sql.ConnectionPool(config, err => { poolA.request() .query("select * from AnyTable", function(err, result) { if (err) message = "Error!"; else { //Do something else message = "Done!"; } }) });
我正在“连接closures错误”。 包括我
poolA.close()
也没有解决问题。
我改变了这个:
new sql.ConnectionPool(config).then(pool => { pool.request() .query("select * from AnyTable") }).then(result => { //Do something else message = "Done!"; sql.close(); }).catch(err => { message = "Error!"; sql.close(); });
现在我得到“那么不是一个函数”的错误。
什么是正确的方法来:
- 创build一个连接,如果它不存在
- 如果连接已经存在,请使用它
我正在得到各种各样的错误。 有人可以帮我解决这个问题吗?
如果你正在使用节点,那么你应该使用诺言,就像你在第二个选项中所做的那样。 所以正确的做法应该如下 –
sql.close() sql.connect(sqlConfig).then(pool => { pool.request() .input('param1', sql.Int, valueParam1) .input('param2', sql.Int, valueParam2) .execute(procedureToExecute).then(result => { // Do whatever you want with the result. })
请记住,链接只有在你从诺言中返回任何东西时才有可能。 在你的情况下,你没有返回连接池或诺言中的任何东西,因此".then is not a function" error.
所以你应该返回池,以防你想再次使用池或返回结果,如果你想使用的结果然后部分。
其次,更好的select是创build连接一次,然后在任何地方使用。 这个概念与MongoDB的ConnectionPooling非常相似,请查看详细信息。 为此,创build一个db.js
文件,如下所示 –
'use strict' const config = require(__dirname + '/index.js') , mssql = require('mssql') , sqlConfig = { , user: config.databaseUsername , password: config.databasePassword , server: config.databaseHost , database: config.database.database pool: { max: 10, min: 0, idleTimeoutMillis: 30000 } } let connection = mssql.connect(sqlConfig,err => { if (err) {throw err} }) module.exports = connection
然后在你的服务器文件或者你想要使用连接的任何模块中连接(需要)上面的内容 –
db = require(process.cwd() + '/config/db.js')
您可以在请求选项中包括这个 –
let options = {db:db} request.options = options
希望这有助于,让我知道,以防您需要任何帮助。
我没有testing它,但看着你的代码,你没有返回任何承诺的第二个() ,所以你会遇到这个错误。然后是不是一个函数 。
尝试在第一个()中添加一个返回 :
new sql .ConnectionPool(config) .then(pool => { return pool .request() .query("select * from AnyTable") }) .then(result => { //Do something else message = "Done!"; sql.close(); }) .catch(err => { message = "Error!"; sql.close(); });