Reputation: 109
I'm hosting a discord.js bot on an ubuntu VPS, and the bot uses MySQL as its database. I turn on the bot, and leave it, and it works fine, but after about 12 hours (it tends to vary), the bot goes offline, because of an error, saying MySQL server disconnected. But, if I restart the bot, MySQL turns back on, and bits of the bot that require the database use the database perfectly fine. I'm not sure if this is an error with MySQL, Node.JS or Ubuntu, but I don't know how to fix it. Thanks!
Upvotes: 0
Views: 638
Reputation: 1245
I had a similar issue when I started using MySQL. The problem is that your bot crashes when it encounters a connection timeout. The MySQL server doesn't go offline, just your connection to it does. Meaning that when you restart your bot it reconnects and everything works.
I encountered two ways of getting around the issue of having to restart the bot manually.
Set up your bot so that it restarts automatically when it encounters a critical error. (Not really the best option but if you want to do it that way it works)
Create a connection pool.
This is by far the better option. It will create a pool of connections ready to go. When you need a connection it will provide you with one and release it after you are done. That way your connection won't time out.
It works like this:
const mysql = require('mysql');
var db_config = {
user: 'root',
password: 'Your password',
database: 'Your database',
// etc
};
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');
});
Upvotes: 1