简体   繁体   English

在 node.js 中使用 mssql 关闭 MSSQL 连接

[英]Close MSSQL connection using mssql in node.js

I am trying to write a script in node.js to query a MSSQL database.我正在尝试在 node.js 中编写一个脚本来查询 MSSQL 数据库。 I am new to javascript, new to node.js, new to VSCode, but I know a few things about SQL.我是 javascript 新手,node.js 新手,VSCode 新手,但我对 SQL 有一些了解。 I have working code, but the connection never seems to close, and I cannot get the values OUT of the function.我有工作代码,但连接似乎从未关闭,我无法从函数中获取值。

SO, I have this chunk of code, which I got from the example from npm :所以,我有这块代码,我从npm的例子中得到:

const sql = require('mssql');
var dbConfig = {
    server:'theServer',
    database:'theDB',
    user:'un',
    password:'pw',
    port:1433
};

sql.connect(dbConfig).then(pool => {
    // Query     
    return pool.request()
    .query('select top 10 * from THE_TABLE')
}).then(result => {
    console.log(result);
}).catch(err => {
    // ... error checks
})

This works, and I can see the 10 results get logged in the console.这有效,我可以看到 10 个结果记录在控制台中。 However, the code never stops running.但是,代码永远不会停止运行。 How do I get the connection to close up and stop?如何让连接关闭并停止?

I really want the results to be saved into a variable, so I changed the code to this:我真的希望将结果保存到一个变量中,所以我将代码更改为:

const sql = require('mssql');
var dbConfig = {
    server:'theServer',
    database:'theDB',
    user:'un',
    password:'pw',
    port:1433
};

let theList;
sql.connect(dbConfig).then(pool => {
    // Query     
    return pool.request()
    .query('select top 10 * from THE_TABLE')
}).then(result => {
    theList= result;
}).catch(err => {
    // ... error checks
})

console.log(theList);

This returns 'undefined' to the console for theList, and again the connection never seems to cose, and the script never shuts down.这将 'undefined' 返回到 theList 的控制台,并且连接似乎永远不会停止,并且脚本永远不会关闭。

How do I just grab the results of the query and move on down the road??我如何只获取查询结果并继续前进?

This worked for me.这对我有用。 There is a .close() method.有一个.close()方法。

const DB = require("mssql")
const config = require("./config.json")
DB.connect(config)
   .then((conn) => 
      conn.query("SELECT * FROM table1")
         .then((v) => console.log(v))
         .then(() => conn.close())
   )

Using Async / Await使用异步/等待

Here's how to open a connection, query, and close using async await以下是如何使用 async await 打开连接、查询和关闭

const sql = require('mssql/msnodesqlv8')

let config = {
    driver: "msnodesqlv8",
    server: serverName,
    database: databaseName,
    options: { trustedConnection: true }
};

// connect to db
let cnn = await sql.connect(config)

// query
let result = await sql.query(query)

// close connection
await cnn.close()

This happens because promises are asynchronous, which happens then when console.log(theList);发生这种情况是因为 Promise 是异步的,当console.log(theList);时会发生这种情况console.log(theList); is executed the query to the database is still in process therefore theList prints undefined because no value has been assigned to it.执行对数据库的查询仍在进行中,因此列表打印未定义,因为尚未为其分配值。

Following your code and if your version of Node.js is 7.6.0 or higher you can do this:按照你的代码,如果你的 Node.js 版本是 7.6.0 或更高,你可以这样做:

const sql = require('mssql');
var dbConfig = {
    server: 'theServer',
    database: 'theDB',
    user: 'un',
    password: 'pw',
    port: 1433
};

let theList;

function executeQuery() {
    return sql.connect(dbConfig).then(pool => {
        // Query     
        return pool.request()
            .query('select top 10 * from THE_TABLE')
    }).then(result => {
        theList = result;
    }).catch(err => {
        // ... error checks
    })
}

async function getData() {
    await executeQuery();
    console.log(theList);
}

getData();

you should call你应该打电话

process.exit()

in the end.最后。 Source Node Docs节点文档

Moreover此外

sql.connect(dbConfig).then(pool => {
    // Query     
    return pool.request()
    .query('select top 10 * from THE_TABLE')
}).then(result => {
    theList= result;
}).catch(err => {
    // ... error checks
})

is an async function是一个异步函数

console.log(theList);

would not wait for it to update the value.不会等待它更新值。

I think you want to do我想你想做

sql.connect(dbConfig).then(pool => {
    // Query     
    return pool.request()
    .query('select top 10 * from THE_TABLE')
}).then(result => {
    theList= result;
}).catch(err => {
    // ... error checks
}).then(function(){
  console.log(theList);
  process.exit(1);
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM