我创建了到数据库的连接,该数据库中有许多与主题相关的表(例如:-subject1,subject2,subject3 ...)。
每个主题表都有两列,即'IndexNo,Result'。我想获得与相同索引号相关的结果。从每个表(一个学生为多个科目的成绩)并将其推入数组。怎么做?
这是我的代码,它返回许多错误。
const mysql = require('mysql');
var connect = mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'results_center'
});
var studentid = 1234;
var results = [];
var i =0;
for(i=1;i++;i<8){
var newResult;
connect.query("select result from subject"+i+" WHERE Index_No = " + studentid,(err,result)=>{
newResult = result;
});
results[i] = result;
}
connect.end()
console.log(results);
答案 0 :(得分:0)
将回调转换为promise并使用Promise.all获取所有结果。
const util = require('util');
const query = util.promisify(connect.query);
var i = 0;
var promises = [];
for(i=1;i++;i<8){
promises.push(query("select result from subject"+i+" WHERE Index_No = " + studentid));
}
Promise.all(promises).then(results => {
connect.end()
console.log(results);
})
答案 1 :(得分:0)
var mysql = require('mysql');
var con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'results_center'
});
con.connect(function(err) {
if (err) throw err;
console.log("connected to mysql");
var subjectResults = [];
var studentid = 1234;
var sql = '';
var i = 0;
for (i = 1; i++; i < 8) {
sql = "select result from subject" + i + " WHERE Index_No = " + studentid;
con.query(sql, function(err, results, fields) {
subjectResults.push(results);
});
}
});