Connecting to MySQL using Node.js
This article explains how to connect to a MySQL database using Node.js, including installation, configuration, and example code.

Important: Node.js must already be installed on your account. A MySQL database and user must also exist before following these steps.

Installing the node-mysql package

  1. Log in to your account using SSH.

  2. Run the following commands:

cd ~
npm install mysql

Connecting to MySQL
After installing the node-mysql package, you can connect to your database using the following example code. Replace dbname, username, and password with your own database details, and adjust the SELECT query to match your table:

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 code creates a MySQL connection object, establishes a connection, executes a query on the employee table, and prints the results.

More information
For details about the node-mysql package, visit node-mysql GitHub.

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

Powered by WHMCompleteSolution