You are currently viewing Connecting to MySQL Database with Node.js: A Simple Tutorial

Connecting to MySQL Database with Node.js: A Simple Tutorial

To establish a connection between Node.js and MySQL, you can utilize the mysql library. Begin by installing the library through npm, the Node.js package manager, using the following command:

npm install mysql

This command will download and install the mysql library, allowing you to utilize its functionalities in your Node.js application. Once installed, you can proceed with configuring the connection to your MySQL database by providing the necessary details such as the host, user, password, and database name.

The example code demonstrates how to connect to the MySQL database, execute a query to fetch users from the users table, and print the results to the console. Finally, the connection is closed using connection.end().


const mysql = require('mysql');

/* database config details */
const connection = mysql.createConnection({
    host    : 'localhost',
    user    : 'root',
    password: '',
    database: 'scratchpad'
});

connection.connect(function(error) {

    if (error) {
        /* handle connection error, if for some reason we couldn't connect to MySQL
                and exit function (return) */
        return;
    }

    console.log('Connected to MySQL database with connection ID ' + connection.threadId);

});

connection.query('SELECT * FROM users', function (error, users, fields) {

    if (error) {
        /* handle query related issues, if for some reason the query couldn't be executed
               and exit function (return) */
        return;
    }

    /* print users out to the console */
    for (const user of users) {
        console.log(`${user.id}, ${user.name}, ${user.email}`);
    }

});

connection.end(function(error) {

    if (error) {
        /* handle disconnection error, if connection for some reason couldn't be ended
                and exit function (return) */
        return;
    }

    console.log('Disconnected from MySQL database with connection ID ' + connection.threadId);

});

Overall, the code demonstrates a basic setup for connecting to a MySQL database using Node.js. It provides a starting point for connecting to a MySQL database in your Node.js application.

If you wish to learn more about Node.js, please subscribe to our newsletter today and continue your Node.js learning journey with us!

Leave a Reply