> ## Knowledge Base Index
> Fetch the complete knowledge base index at: https://help.sparkedhost.com/sitemap.xml
> Use this file to discover available pages before exploring further.
> Pure-Markdown content can be obtained by appending a '.md' suffix to the content URLs listed in the sitemap (without the trailing slash).

# How to connect to a Database (MySQL) in Node.JS

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](#1-prerequisites)
* [Setting up the Connection](#1-setting-up-the-connection)
* [Using the Connection](#1-using-the-connection)
* [Useful Thinks to Know](#1-useful-thinks-to-know)

---

# Prerequisites

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](/en/article/how-to-install-dependencies-packages-on-node-discord-bot-hosting-lan7gn/).

# Setting up the Connection

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

```js
const mysql = require('mysql')

const connection = mysql.createPool({
    host: "1.2.3.4",
    user: "username",
    password: "password",
    database: "database"
})

module.exports = connection

```

# Using the 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.

```js
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])
})
```

# Useful Things to Know

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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).

```js
// 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](https://billing.sparkedhost.com/submitticket.php).

---

Created By: Greg K