# Connecting to MySQL using Node.js

> Install a MySQL package for Node.js and connect your Node.js application to a MySQL database, with example code.

Source: https://helpcenter.ruachost.com/developers/databases/connecting-to-mysql-using-node-js/

**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.

> **Caution:**
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](https://github.com/mysqljs/mysql).
