Skip to Content

How to Query A MySQL Database with NodeJS

In this tutorial, you'll learn how to query a MySQL database with NodeJS and the MySQL library from the npm registry.

Ad - Web Hosting from SiteGround - Crafted for easy site management. Click to learn more.
Advertising Disclosure: I am compensated for purchases made through affiliate links. Click here for details.


First, you'll need to download and install NodeJS. The minimum version requirement for this library is v0.6.

Next, you'll need to install the MySQL library via the command line:

npm install mysql

Code Examples

Query a database

var mysql = require("mysql");

var connection = mysql.createConnection({
host: "localhost",
user: "[username]",
password: "[password]",
database: "[database_name]"


connection.query("SELECT FirstName, LastName FROM Employees",
function(error, results, fields) {
if (error) {
throw error;

console.log("There are " + results.length + " employees.");


First, we include the MySQL library and assign it to the mysql variable. Second, we create a connection to the database and assign it to the connection variable. Within the mysql.createConnection() method, replace the database name and credentials in the object passed with the correct values.

Next, we'll connect to our database and run a query against our hypothetical Employees table. You can run any query you need that matches your table structures. The processing halts when an error is thrown. Otherwise, the console logs the number of employees returned in the record set.

After running a query and processing the results, it's very important to close your existing database connections. Too many concurrent connections can cause further query errors, which can be especially troublesome in production environments. In that case, the MySQL service would either need to be restarted or the previous connections would need to time out before a new connection can be established.

Loop over query results

To loop over the results of the same query, you could use the following code:

connection.query("SELECT FirstName, LastName FROM Employees",
function(error, results, fields) {
if (error) {
throw error;

for (var i = 0; i < results.length; i++) {
console.log("Employee: " + results[i].FirstName + " " + results[i].LastName);


This tutorial showed you how to install NodeJS and the MySQL dependency, set up a database connection, query a database, and loop over the results.

Posted by: Josh Rowe
Last Updated: September 01, 2023
Created: July 27, 2023


There are no comments yet. Start the conversation!

Add A Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.