How to connect to a Database (MySQL) in Node.JSPrerequisitesSetting up the ConnectionUsing the ConnectionUseful Things to Know

Articles on: Discord Bot Hosting


Databases are SUPER important if you would like to store data. You can use it to store shop items, user statistics, mini-game data, and more! Databases are extremely useful in discord bots and this is why you should learn how to connect to a database in Node.JS.


Table of Contents


  • Prerequisites

  • Setting up the Connection

  • Using the Connection

  • Useful Thinks to Know

Since we are going to use MySQL, We will need to install the


mysql


package to our project. If you do not know how to install a package on our Apollo panel, click here.

Start of my adding the following code into a new file in your project. In this case, we will name this file


connect.js


.


undefined const mysql = require('mysql') const connection = mysql.createPool({ host: "1.2.3.4", user: "username", password: "password", database: "database" }) module.exports = connection


Since we exported the connection from the


connect.js


file, we are able to import it to other files in the project and use the connection. Here is an example of how to use the connection.


undefined const connection = require('./connect.js') const id = "398514225435377673" connection.query(`SELECT * FROM characters WHERE discordId = ?`, [id], function (err, result) { if (err) { console.log(err) } console.log(result[0]) })


To keep your project clean, you are able to have all of your database functions in a single file and export those function for further use in other parts of your project. In thise case, we have this piece of code in a file called


databaseFunctions.js


. Here is an example:

Note: We are using a promise in this example. The promise is there as other parts of the application will need to wait for the database to fetch the data. The fetching process is not instant. Find our more about promises here.


undefined // databaseFunctions.js const connection = require('./connect.js') exports.getUser= async function (id) { return new Promise((resolve, reject) => { connection.query(`SELECT * FROM users WHERE discordId = ?`, [id], function (err, result) { if (err) { log.error(err) reject(err) } resolve(result) }) }) } // otherFile.js const databaseQuery = require('databaseFunctions.js') const id = "398514225435377673" //Method 1 const userInfo = await databaseQuery.getUser(id) console.log(userInfo) //Method 2 databaseQuery.getUser(id).then((userInfo) => { console.log(userInfo) }).catch((err) => { conslle.log(err) })


If you require any further assistance, please create a ticket here.

Created By: Greg K


Updated on: 01/07/2023

Actualizado el: 31/07/2024

¿Este artículo te resultó útil?

Comparte tu opinión

Cancelar

¡Gracias!