简体   繁体   中英

How to connect to a database and get data from multiple tables in nodejs?

I created a connection to a database where many tables related to subjects (eg:- subject1, subject2, subject3 ...).

Every subject table has two columns they are, 'IndexNo, Result'. I want to get results related to the same index no. from every table (One student results for many subjects) and push it into an array. How to do that?

This is my code and it returns many errors.

    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);

Convert callback to promise and use Promise.all to get all result.

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);
})
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);
        });
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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