If you’re working on a Node.js app, you often need a database to store information. MySQL is one of the most popular database systems available today. In this guide, we’ll walk you through how to connect your MySQL database with your Node.js app.
In order to use MySQL databases with NodeJS, you’ll need to use a Node library. There are multiple options, but the most popular Node.js library to connect to MySQL is mysqljs/mysql
. Simply use npm to install it to your package.json
npm install mysql
You can find additional documentation for mysqljs/mysql
on the project’s GitHub repository.
You’ll need to have your MySQL credentials. You can use this guide to find your credentials.
Once you have your credentials, import the mysql package and create a new connection object by calling createConection()
. In the example below, we pass in our credentials to create the connection.
const mysql = require(‘mysql’);
const connection = mysql.createConnection({
host: ‘localhost’,
user: ‘myUser’,
password: ‘myPassword’,
database: ‘myDB’
});
We can then initialize the connection using the connect()
method on our connection object:
connection.connect()
Once you have established your connection, you can query your MySQL database using Node. To create and run a query, use the query()
method like this:
connection.query(‘SELECT ? as message’, [‘Arctype Archive: Your #1 Database Resource’], (err, res, fields) => {
if (err) {
return console.error(err.message);
}
console.log(res);
});
You can also pass variables to query()
for both the text and values parameters like this:
const text = 'INSERT INTO Users(username, email) VALUES(?, ?) RETURNING *'
const values = ['Arctype', 'test@Arctype.com']
connection.query(text, values, (err, res, fields) => {
if (err) {
return console.error(err.message);
}
console.log(res);
});
Now that you’ve connected MySQL to your Node.js app, you often need to add or edit data. We recommend using an SQL client to do so. Check out our guide for setting up MySQL with Arctype in this tutorial.