This article demonstrates how to connect to a MySQL database using Node.js.

Connecting to MySQL using the node-mysql package

The node-mysql package makes it simple to connect to a MySQL database using Node.js. However, before you can do so, you must first install the node-mysql package on your account. Follow these steps to accomplish this:

  1. Log in to your account using SSH.
  2. Type the following commands:
    cd ~
    npm install mysql
    
Code sample

After you install the node-mysql package, you are ready to work with actual databases. The following sample Node.js code demonstrates how to do this.

In your own code, replace dbname with the database name, username with the MySQL database username, and password with the database user's password. Additionally, you should modify the SELECT query to match a table in your own database:

var mysql      = require('mysql');
var connection = mysql.createConnection({
    host     : 'localhost',
    database : 'dbname',
    user     : 'username',
    password : 'password',
});

connection.connect(function(err) {
    if (err) {
        console.error('Error connecting: ' + err.stack);
        return;
    }

    console.log('Connected as id ' + connection.threadId);
});

connection.query('SELECT * FROM employee', function (error, results, fields) {
    if (error)
        throw error;

    results.forEach(result => {
        console.log(result);
    });
});

connection.end();

This example constructs a MySQL connection object that connects to a MySQL database. After connecting to the database, you can use the query method to execute raw SQL commands (in this case, a SELECT query on the employee table).

Was this answer helpful? 0 Users Found This Useful (0 Votes) mySQL, mySQL connection