Query mysql on Node-JS Not Working

Asked

Viewed 123 times

-1

I am developing a Node application in which I need to do some query’s in mysql, however a simple query of select is not working. follows the code of the passage

function processTag(tagNumber, tagBdId, datesIndex, logdata, deviceId)
{
var dataValues = [];
var runningQuerys = 0;

//faz a query de insert no banco de dados
var sqlCon = mysql.createConnection({
    host: "localhost",
    user: "%myuser%",
    password: "%mypass%"
});


sqlCon.connect(function(err) {
    console.log("connected to mysql");
    if (err) throw err;

    for(var i=0; i<datesIndex.length; i++)
    {
        //aguarda querye ficar pronta
        if(runningQuerys > 0)   {i-=1; continue;}

        //fa procedimentos de adicionar tag ao banco de dados
        if(datesIndex[i+1])
        {   
            date = logdata.substring(datesIndex[i][0], datesIndex[i][1]);
            value = logdata.substring(datesIndex[i][1], datesIndex[i+1][0]);
        }
        else
        {   
            date = logdata.substring(datesIndex[i][0], datesIndex[i][1]);
            value = logdata.substring(datesIndex[i][1], null);
        }

        //formata data
        date = date.replace("2?","");

        //retira ultima parte da data
        date = date.substring(0,date.lastIndexOf("^"));
        date = date.substring(0,date.lastIndexOf("^"));

        //transforma data em datetime
        date = new Date(date);

        //poe a datea em um formato sql
        date = date.getFullYear()+'-'+(date.getMonth() + 1).toString().padStart(2, '0')+'-'+date.getDate().toString().padStart(2, '0')+' '+date.getHours().toString().padStart(2, '0')+':'+date.getMinutes().toString().padStart(2, '0')+':'+date.getSeconds().toString().padStart(2, '0');    

        //formata valor
        patt =  new RegExp("3\\?"+tagNumber+"\\^([\\d+\\.]+)");
        value = value.match(patt);

        var valueQuery = "SELECT null, "+tagBdId+", "+value[1]+", `date`.`id`, 1, '"+deviceId+"' FROM `sync`.`date` WHERE `date`.`date` = '"+date+"';"

        //faz uma query no banc de dados sql  
        runningQuerys += 1;

        console.log('------ fazendo query -> '+i.toString());    
        console.log(valueQuery);    

        console.log(sqlCon.state);
        sqlCon.query(valueQuery, (err, result) => {
            if (err) throw err;   
            console.log(result.sql);
            console.log("----- Query terminada");
            runningQuerys--; 
            dataValues.push(result[0]);
        });

        //faz query por query de insert na falta de opção kkkkkk :'(
        //query += "INSERT INTO `sync`.`tag_value` (`id`, `tag`, `value`, `date`, `project`, `device_imei`) SELECT null, "+tagBdId+", "+value[1]+", `date`.`id`, 1, '"+deviceId+"' FROM `optync`.`date` WHERE `date`.`date` = '"+date+"' ON DUPLICATE KEY UPDATE `tag_value`.`id`=`tag_value`.`id`;";     
    }         
    console.log(dataValues);
/*
    console.log("query size = " +(query.length/1024.00).toString()+ " Kb");


    //faz uma query no banc de dados sql  
    con.query(query, function (err, result) {
        if (err) throw err;                
    });

    console.log("Processando tag > "+tagNumber);
    console.log("Processando Date > "+date);
    */

});

console.log("Result: Tags Values adicionadas ao banco de dados");
}  

using the library

var mysql = require('mysql');

the program gets stuck in the query part

the last answers on the screen are from this section below and is waiting for the query that is not executed

console.log(valueQuery);   
console.log(sqlCon.state);


I still don’t understand what happened. Maybe it is that this query is called in a function within the Results of another query, but finally, I have re-structured all the programming and worked.

I’ll keep it open for now, in case anyone knows what happened in this case

  • Which error message appears?

  • no message appears ... the above code waits for the query to finish but it does not deliver errors.. and the connection status is "Connected"

  • The time you log into the array is prior to entering the results within the array.

1 answer

0

The problem is in the connection parameters with the database, the database is missing. I simulated the situation here and gives exception error. Another thing I noticed is that the callback parameter "result" does not have the "sql" property. My example is below:

    const sqlCon = mysql.createConnection({
       host: "host",
       user: "user",
       password: "pass",
       database: "database"
    });

    sqlCon.query("select * from users limit 1", (err, result) => {
       if (err) throw err;   
       console.log(result[0].first_name);
       console.log("----- Query terminada");
   });
  • Not yet.. This Function with this query is called in the . on("end", () => {} function of another query, will this be influencing?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.