简体   繁体   English

NODEJS mysql 结果未定义

[英]NODEJS mysql result is undefined

Hello i got problem with node mysql.您好,我遇到了节点 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. 20/30 分钟。 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?有人知道如何让它不仅能工作 20 分钟吗?

MySQL connections time out. MySQL 连接超时。 I wouldn't of thought it would within 30 minutes, but it sounds to me like this is the issue.我不认为它会在 30 分钟内完成,但在我看来这就是问题所在。 Instead connect using pool.而是使用池连接。 Also its much better to put this outside the client.on('message', message => { });将它放在client.on('message', message => { });之外也更好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!");作为旁注,如果您想检查是否有结果,可以使用if(typeof result[0] === 'undefined') return console.log("It isn't defined!");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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