Node.js MySQL integration lets a Node.js application connect to a MySQL database, run SQL queries, and work with the returned rows inside JavaScript code. For a basic callback-based setup, the mysql package is enough to connect, query, insert, update, and delete records from a MySQL server.
In this tutorial, we shall learn how to install the MySQL module in Node.js using npm, create a database connection, run a SELECT query, understand the callback arguments, and follow safer query practices such as parameterized values.
Node.js MySQL Tutorial Topics
Following is a quick view of topics we are going to learn about Node.js MySQL.
- Install Node.js MySQL module
- Node.js MySQL Connect Database
- MySQL Queries in Node.js
- MySQL SELECT FROM Table Query
- MySQL INSERT INTO Table Query – Node.js MySQL Tutorial to insert records into Table
- MySQL WHERE clause with SELECT Query
- MySQL ORDER BY clause with SELECT Query– Node.js MySQL Tutorial to arrange records in an order based on one of the properties of records in table.
- MySQL UPDATE Table Query
- MySQL DELETE Records Query
- Usage of MySQL Result Object in callback function
- Usage of MySQL Fields Object in callback function
- Usage of MySQL Error Object in callback function

Install MySQL Module in Node.js Using npm
As Node.js MySQL is an external module, it can be installed using NPM (Node Package Manager). Create or open your Node.js project folder first, and then install the package from the terminal.
Run the following command in terminal or command prompt to install MySQL module and use it in Node.js programs.
$ npm install mysql
After successful install, you may use MySQL module in node.js programs by declaring its usage with a require statement as shown below.
var mysql = require('mysql');
Note – If MySQL module is not installed, but used in Node.js programs, you might get the Error : Cannot find module ‘mysql’.
For a fresh Node.js project, it is also common to initialize a package.json file before installing dependencies.
npm init -y
npm install mysql
Create Connection to MySQL Database in Node.js
To create a connection variable with IP Address (of server where MySQL server is running), User Name and Password (of user that has access the MySQL database). An example is provided below :
var con = mysql.createConnection({
host: "localhost", // ip address of server running mysql
user: "arjun", // user name to your mysql database
password: "password", // corresponding password
database: "studentsDB" // use this database to querying context
});
The connection object only stores the connection configuration. To actually connect to MySQL, call con.connect() and handle the error callback.
con.connect(function (err) {
if (err) {
console.error("Error connecting to MySQL:", err.message);
return;
}
console.log("Connected to MySQL database.");
});
In real projects, avoid hard-coding the database password directly in source code. A better practice is to read connection values from environment variables or a configuration file that is not committed to version control.
Node.js MySQL Connection Settings Explained
| Connection option | Purpose in Node.js MySQL | Example value |
|---|---|---|
host | MySQL server hostname or IP address. | localhost |
user | MySQL user name that has permission to access the database. | arjun |
password | Password for the given MySQL user. | password |
database | Default database used for queries. | studentsDB |
port | MySQL port number, if it is not the default port. | 3306 |
SELECT FROM Query in Node.js MySQL
MySQL SELECT Query is used to select some of the records (with some of their properties if required) of a table.
con.query("SELECT * FROM studentsDB.students", function (err, result, fields) {
// if any error while executing above query, throw error
if (err) throw err;
// if there is no error, you have the result
console.log(result);
});
The callback function receives three useful arguments:
errcontains the MySQL error object if the query fails.resultcontains the returned rows for SELECT queries, or query metadata for INSERT, UPDATE, and DELETE queries.fieldscontains information about the selected columns for SELECT queries.
Run a Complete Node.js MySQL SELECT Example
The following example shows a small working program that connects to MySQL, selects rows from the students table, prints the rows, and then closes the connection.
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "arjun",
password: "password",
database: "studentsDB"
});
con.connect(function (err) {
if (err) {
console.error("Connection failed:", err.message);
return;
}
con.query("SELECT id, name, age FROM students", function (err, result, fields) {
if (err) {
console.error("Query failed:", err.message);
con.end();
return;
}
console.log(result);
con.end();
});
});
A sample result may look like the following. The exact output depends on the records present in your MySQL table.
[
{ id: 1, name: 'Ravi', age: 20 },
{ id: 2, name: 'Meena', age: 21 }
]
Use Parameterized Values in Node.js MySQL Queries
When a value comes from user input, do not build the SQL string by directly joining text. Use placeholders with values supplied separately. This keeps the query easier to read and helps avoid SQL injection mistakes.
var studentId = 1;
con.query(
"SELECT id, name, age FROM students WHERE id = ?",
[studentId],
function (err, result) {
if (err) throw err;
console.log(result);
}
);
The ? placeholder is replaced using the value from the array. This is preferable to writing a query like "WHERE id = " + studentId.
Insert Records with Node.js MySQL
Use the INSERT statement when you want to add a new row to a MySQL table from Node.js. The following example inserts one student record using placeholders.
var student = {
name: "Kiran",
age: 22
};
con.query(
"INSERT INTO students SET ?",
student,
function (err, result) {
if (err) throw err;
console.log("Inserted row id:", result.insertId);
}
);
For INSERT queries, the result object usually contains useful metadata such as insertId and affectedRows.
Update Records with Node.js MySQL
Use UPDATE when you want to change existing rows. Always include a proper WHERE condition unless you intentionally want to update all rows in the table.
con.query(
"UPDATE students SET age = ? WHERE id = ?",
[23, 1],
function (err, result) {
if (err) throw err;
console.log("Rows updated:", result.affectedRows);
}
);
Delete Records with Node.js MySQL
Use DELETE when you want to remove rows from a table. As with UPDATE, the WHERE clause is important because a DELETE query without a condition may remove every row from the table.
con.query(
"DELETE FROM students WHERE id = ?",
[1],
function (err, result) {
if (err) throw err;
console.log("Rows deleted:", result.affectedRows);
}
);
Close Node.js MySQL Connection After Queries
After the database work is complete, close the MySQL connection with con.end(). This allows Node.js to finish the process cleanly when there is no more work to do.
con.end(function (err) {
if (err) {
console.error("Error while closing connection:", err.message);
return;
}
console.log("MySQL connection closed.");
});
Node.js MySQL Common Errors and Fixes
| Error or issue | Likely reason | What to check |
|---|---|---|
Cannot find module 'mysql' | The package is not installed in the current project. | Run npm install mysql inside the project folder. |
ER_ACCESS_DENIED_ERROR | User name or password is incorrect, or the user does not have permission. | Check MySQL credentials and database grants. |
ECONNREFUSED | MySQL server is not running or the host/port is wrong. | Start MySQL and verify host and port. |
ER_BAD_DB_ERROR | The database name does not exist. | Create the database or correct the database value. |
| Query runs but returns an empty array | No rows match the query condition. | Verify table data and WHERE clause values. |
mysql and mysql2 Packages in Node.js
This tutorial uses the mysql package because it matches the callback-based examples used here. Many current Node.js projects also use mysql2, especially when they prefer promise-based code, prepared statement support, or compatibility with modern async/await style.
If you are following this tutorial exactly, install mysql. If you are starting a new application and want promise-based examples, check the package documentation and choose the driver that fits your project style.
Node.js MySQL QA Checklist for Tutorial Review
- Verify that
npm install mysqlis run inside the same folder where the Node.js file is executed. - Confirm that the MySQL server is running before testing the connection example.
- Check that the database name, table name, and column names in the examples match your local schema.
- Use placeholders for user-provided values in SELECT, INSERT, UPDATE, and DELETE queries.
- Close the database connection after the example finishes, or use connection pooling in larger applications.
FAQs on Node.js MySQL
Which npm package is used for Node.js MySQL examples?
This tutorial uses the mysql npm package. It provides a callback-based API for connecting Node.js programs to a MySQL database and running SQL queries.
Why do I get Cannot find module ‘mysql’ in Node.js?
You get this error when the mysql package is not installed in the current Node.js project, or when the script is executed from a different project folder. Run npm install mysql in the project directory and execute the script again.
How do I prevent SQL injection in Node.js MySQL queries?
Use placeholders such as ? and pass values separately in an array. Do not join raw user input directly into a SQL string.
What is the result object in Node.js MySQL?
For SELECT queries, the result object contains the rows returned by MySQL. For INSERT, UPDATE, and DELETE queries, it contains metadata such as affected rows and, where applicable, the inserted row id.
Should I close the MySQL connection in Node.js?
Yes. For small scripts and examples, call con.end() after your queries are complete. In larger applications, connection pooling is usually preferred so that multiple requests can reuse database connections efficiently.
Conclusion: Using MySQL Queries in Node.js
In this Node.js Tutorial, we have learnt to install MySQL module/package in Node.js using npm. We also created a MySQL connection, executed SELECT, INSERT, UPDATE, and DELETE queries, used placeholders for safer values, and reviewed common connection errors.
TutorialKart.com