To connect to a MySQL database in Node.js, you can use the mysql
package which is available on npm. You need to have MySQL installed on your machine before you can connect to a MySQL database using Node.js.
Before starting, you must do node js install following these tutorials.
You can download and install MySQL from the official MySQL website at https://dev.mysql.com/downloads/. Once you have installed MySQL, you can create a database and a user with appropriate permissions to access the database.
Node js MySql connection example
Simple example code basic steps to connect to a MySQL database using Node.js:
1. Install the mysql
package by running the following command in your terminal:
This will install the latest version of the MySQL module and its dependencies in your project directory node_modules
folder.
npm install mysql
2. In your Node.js file, require the MySQL module by adding the following line at the top:
const mysql = require('mysql');
3. Create a connection object by passing in the required credentials to the mysql.createConnection()
method, like so:
const connection = mysql.createConnection({
host: 'localhost',
user: 'yourusername',
password: 'yourpassword',
database: 'yourdatabase'
});
4. Use the connection.connect()
method to establish a connection to the database:
// connect to the database
connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
5. Execute queries on the database using the connection.query()
method:
connection.query('SELECT * FROM users', (err, rows) => {
if (err) throw err;
console.log('Data received from database:\n');
console.log(rows);
});
6. Close the connection when you’re done with it by calling the connection.end()
method:
connection.end((err) => {
if (err) {
console.error('Error closing database connection: ', err);
return;
}
console.log('Database connection closed!');
});
Complete code
Make sure to replace yourusername
, yourpassword
, and yourdatabase
with the actual credentials for your MySQL database. This code connects to the database, selects all the rows from the users
table, logs the results to the console, and then closes the connection.
const mysql = require('mysql');
// create a connection object
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'test'
});
// connect to the database
connection.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
Run “app.js”
node app.js
Output:
You can use this as a starting point and build upon it to create more complex database interactions.
Comment if you have any doubts or suggestions on this first node js database topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version