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.

3
  • 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? Commented Sep 5, 2019 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. Commented Sep 5, 2019 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. Commented Sep 5, 2019 at 15:25

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.