1

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.

  • 1
    Has `process.env.DB_DATABASE` come in correctly? Can you humor us and do `console.log(process.env.DB_DATABASE)` just to be safe? – esqew Sep 05 '19 at 15:12
  • @esqew Okay. I fixed this thing now. It was caused by the line `require('dotenv').config();` being after the connection was created. – OfficialCRUGG Sep 05 '19 at 15:24
  • Great to hear! Please consider posting as a self-answer so that future visitors to the question can clearly see how you solved the problem. – esqew Sep 05 '19 at 15:25

1 Answers1

2

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! :)