简体   繁体   中英

Why MySQL connection lost in nodejs?

I am creating a facebook chatbot using node js and to store data I used MySQL Database. Currently it is working fine. But, I have a question that, should I need to close the database connection?

I tried to do it but when I close the connection then in the next attempt it is throwing an error that No SQL Connection found

Please tell me the correct way of how to close database connection and reuse it

let databaseConnection = () =>{
    let conn = mysql.createConnection({
        host: "",
        user: "",
        password: "",
        database: "",
        port: ""
    });

    conn.connect(function (error) {
        if (error) {
            console.log("Error when connecting to db ",error);
            setTimeout(databaseConnection, 2000);
        }
        else {
            console.log("Connected");
        }
    });

    conn.on('error',function(err){
        console.log('db error', err);
        if(err.code === 'PROTOCOL_CONNECTION_LOST') {
            databaseConnection();
        }else{
            throw err; 
        }
    });
    
    return conn;
}

conn = databaseConnection();

for (let i=0;i<10;i++){
    query = "SELECT name FROM info where id=?";
    value = i
    conn.query(query,value, function (err, result, fields) {
        if (err) throw err;
        console.log(result);
        console.log("Data Fetched Successfully.")
    })
    conn.end()
}

You should end your connection after the loop

for (let i=0;i<10;i++){
    query = "SELECT name FROM info where id=?";
    value = i
    conn.query(query,value, function (err, result, fields) {
        if (err) throw err;
        console.log(result);
        console.log("Data Fetched Successfully.")
    })
}
conn.end()

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