How To Use Node.js With MySQL Database

If you want to operate a MySQL database through a programming language like JavaScript (Node.js), you need to connect the MySQL database with the language first. In this tutorial, you will learn how to make a connection between JavaScript (Node.js) and MySQL DB.

Node.js MySQL Database Connection

To make database connection with MySQL DB we will use the npm mysql2 package. Let’s see how you can use this package –

1. First, install this package with the help of the following command.

npm install --save mysql2

2. After that, import this package in your JS file.

import mysql from 'mysql2';

3. The mysql2 package has a method called createConnection() that is used to create a connection with the MySQL database.

import mysql from 'mysql2';

const connection = mysql.createConnection({
    options
});

4. We have to put the database information inside the createConnection() method with the help of the Options.

  • Database name: my_test_db
  • Host of the DB: localhost
  • User of the DB: root
  • Password of the DB: your_db_password
import mysql from 'mysql2';

// Replace the database details according to yours
const connection = mysql.createConnection({
    host:'localhost',
    user:'root',
    password:'',
    database:'my_test_db'
});

5. The connection has a callback method called .connect((error) => {}) use this method to check database is connected successfully.

import mysql from 'mysql2';

const connection = mysql.createConnection({
    host:'localhost',
    user:'root',
    password:'',
    database:'my_test_db'
});

// Verify that the database is connected successfully
connection.connect((error) => {
    if(error){
        console.error(error);
        return;
    }
    console.log('The database is successfully connected.');
})
PS c:\#project\node-js\learn-node-js> node index.js
The database is successfully connected.

Want to Use Promise Connection:

If you want to use Promises mysql2 also supports Promises. Here’s an example –

import mysql from 'mysql2/promise';

try{
    const connection = await mysql.createConnection({
        host:'localhost',
        user:'root',
        password:'',
        database:'my_test_db'
    });
}
catch(err){
    console.log(`${err.name}: ${err.message}`);
}

MySQL2 Connection Pool:

MySQL2 also exposes a .promise() function on Pools, so you can create a promise and non-promise connections from the same pool. Here’s an example –

import mysql from 'mysql2';

// Non-promise connection
const connection = mysql.createPool({
    host:'localhost',
    user:'root',
    password:'',
    database:'my_test_db'
});

// Promise connection
const connectionPromise = connection.promise();

// Query with non promise
connection.query('SQL query...', (err, row, fields) => {
    ...
});

// Query with Promise connection
connectionPromise.query('SQL query...')
.then(([row,fields]) => {
    ...
})
.catch(err => {
    ...
})

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to ensure that we give you the best experience on our website. Privacy Policy