Search code examples
mysqlnode.jsnode-mysql2

NodeJS mysql2 "Error: No database selected"


I am currently trying to make a little Discord Bot using the mysql2 package for Database Connection. When I set up my DB like this:

const con = mysql.createConnection({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    database: process.env.DB_DATABASE,
    password: process.env.DB_PASSWORD,
    port: process.env.DB_PORT
});

(the data from my .env file is 100% right) and then do a query like this:

client.database.query("SELECT * FROM `guilds_settings` WHERE `guild` = ?", [message.guild.id], (err, results) => {
        if(err) {
            return client.log.error("Failed loading language for guild " + message.guild.id + ": " + err);
        }
        message.reply(results[0].language);
});

(client.database = con) This just gives me the error "Not database selected", even though I selected the database when creating the connection.


Solution

  • Thanks to a little tip from esqew I was able to fix it. In my case it was caused my the string for the database was undefined, because I did the stuff to load the .env file after creating the connection. Be sure to always put stuff like this at the beginning! :)