我正在尝试将数据库中的数据保存到全局变量中,以便在其他脚本中使用
我正在使用sqlServer和nodejs
var sql = require("mssql");
const config = {
server : "",
database : "",
user : "",
password : "",
};
var table = [];
function getCord() {
// Create instence of connection
var conn = new sql.ConnectionPool(config);
var req = new sql.Request(conn);
// Connecting to database
conn.connect(function(err){
if(err){
console.log(err);
return;
}
// Getting result
var queryString = "SELECT * FROM XXXX";
req.query(queryString, function(err, recordset){
if(err){
console.log(err)enter code here;
return;
}
else{
//console.log(JSON.stringify(recordset));
table = recordset;
}
conn.close();
});
});
console.log(JSON.stringify(table));
}
getCord();
这就是我得到的结果
C:\ Users \ Lara \ Desktop \ soap_examp \ nodejs>节点connect.js []
答案 0 :(得分:0)
您已创建一个同步函数,并且对数据库的查询是异步的。因此,当console.log
升高时,您的req.query仍处于待处理状态。您可以这样做
function getCord() {
return new Promise((resolve, reject) => {
// Create instence of connection
var conn = new sql.ConnectionPool(config);
var req = new sql.Request(conn);
// Connecting to database
conn.connect(function(err){
if(err){
console.log(err);
return;
}
// Getting result
var queryString = "SELECT * FROM XXXX";
req.query(queryString, function(err, recordset){
if(err){
console.log(err)enter code here;
return;
}
else{
//console.log(JSON.stringify(recordset));
table = recordset;
}
conn.close();
resolve(true);
});
});
});
}
getCord().then(() => console.log(table));