简体   繁体   中英

NODEJS mysql result is undefined

Hello i got problem with node mysql.

client.on('message', message => {

   var con = mysql.createConnection({
      host: config.host,
      user: config.user,
      password: config.password,
      database: config.database
   });

   //con.connect(function (err){ i was try with this
      //if(err) console.log(err); i was try with this
      con.query(`SELECT * FROM servers`, function (err, result){
            result.forEach(row => {
               if(row.guild === message.guild.id){
                 //some code
               }
            }
       }

For 20/30 min. everything is okay. But then i got crash. I found one solution.

client.on('message', message => {

   var con = mysql.createConnection({
      host: config.host,
      user: config.user,
      password: config.password,
      database: config.database
   });

      con.query(`SELECT * FROM servers`, function (err, result){
           if(result){
             result.forEach(row => {
               if(row.guild === message.guild.id){
                 //some code
               }
             }
           }else{
                console.log("no result");
           }
       }

But then i got only spam "no result" and nothing works. Someone have idea how to get this still work not only for 20 min?

MySQL connections time out. I wouldn't of thought it would within 30 minutes, but it sounds to me like this is the issue. Instead connect using pool. Also its much better to put this outside the client.on('message', message => { }); , then just reference it from inside. Example:

const mysql = require('mysql');

var db_config = {
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'mybots-db'
};

var con = mysql.createPool(db_config);
con.getConnection(function (err, con) {
    if (err) {
        connection.release();
        console.log(' Error getting mysql_pool connection: ' + err);
        throw err;
    }
    console.log('Connected to Database');
});



client.on('message', message => {
    //Your code here
});

As a side-note, if you want to check if you've got a result it can be done easier with if(typeof result[0] === 'undefined') return console.log("It isn't defined!");

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