App overview screenshotSQL and Database Guides
PostgresMySQL
Try our free SQL Client
Tools
Connecting to MySQL
Connecting to drivers
Installing MySQL
Setting up MySQL
MySQL   >   
Connecting to drivers   >   
MySQL with NodeJS

Learn How To Connect MySQL with NodeJS

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.

What You’ll Need

Installing The mysqljs/mysql Connector

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.

Connecting to Your MySQL Database

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()

Querying your database

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);
});

Using an SQL Client with MySQL and Node.js

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.

Want to ask for help on databases or SQL? Join our Discord community.