📂 Node.js – MySQL: Introduction & Setup
Estimated reading: 3 minutes 659 views

Node.js – MySQL Get Started – Connect, Query, and Manage Data with MySQL


Introduction – Why Use MySQL with Node.js?

MySQL is one of the most popular open-source relational databases. When paired with Node.js, it becomes a powerful backend stack for building data-driven applications, such as dashboards, CMS, e-commerce systems, and APIs.

Using the mysql or mysql2 module, Node.js can easily connect to MySQL databases, perform CRUD operations, and manage schema or transactions efficiently.

In this guide, you’ll learn:

  • How to set up and install MySQL module in Node.js
  • Connect Node.js to a MySQL database
  • Run basic SQL queries (SELECT, INSERT, etc.)
  • Handle errors and close connections

Step 1 – Install MySQL Module

Install the official mysql module using npm:

npm install mysql

Or use mysql2 if you prefer Promise-based support:

npm install mysql2

Step 2 – Connect Node.js to MySQL

Create a file db.js to handle connection:

const mysql = require('mysql');

// Create connection object
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '', // set your MySQL root password
  database: 'testdb'
});

// Connect to database
connection.connect((err) => {
  if (err) throw err;
  console.log('Connected to MySQL database!');
});

module.exports = connection;

Output:

Connected to MySQL database!

Step 3 – Run Basic SQL Query (SELECT)

const db = require('./db');

db.query('SELECT * FROM users', (err, results) => {
  if (err) throw err;
  console.log('User List:', results);
});

Insert Data into MySQL

const db = require('./db');

const user = { name: 'John Doe', email: 'john@example.com' };
db.query('INSERT INTO users SET ?', user, (err, result) => {
  if (err) throw err;
  console.log('User added with ID:', result.insertId);
});

Output:

User added with ID: 5

Close MySQL Connection

db.end((err) => {
  if (err) throw err;
  console.log('Connection closed.');
});

Best Practices for Node.js + MySQL Integration

Practice Benefit
Use pool for high traffic appsBetter connection management
Use placeholders (?) in queriesProtects against SQL injection
Always close unused connectionsPrevents memory leaks and overload
Separate config in .env filesEnhances security and environment setup
Use async/await with mysql2/promiseCleaner and more readable code

Summary – Recap & Next Steps

You’ve now connected a Node.js app to a MySQL database using the mysql module. With this foundation, you can perform basic CRUD operations and begin building more complex database-driven applications.

Key Takeaways:

  • Use mysql.createConnection() to connect
  • Run SQL queries using query() method
  • Handle connections, results, and errors properly
  • Use placeholders (?) to prevent SQL injection

Real-world relevance:
Used in full-stack web apps, REST APIs, CMS backends, analytics dashboards, booking systems, and inventory tools.


FAQs – Getting Started with MySQL in Node.js


Which MySQL module should I use: mysql or mysql2?
mysql is stable and widely used. Use mysql2 for Promises and better performance.


Can I use MySQL with async/await in Node.js?
Yes, use mysql2/promise for Promise support and async handling:

const mysql = require('mysql2/promise');
const conn = await mysql.createConnection({ ... });

How do I prevent SQL injection?
Use ? placeholders in your queries:

db.query('SELECT * FROM users WHERE id = ?', [userId]);

How do I handle database errors?
Always check the err object in the callback or use try/catch with Promises.


Can I reuse the connection across files?
Yes. Export the db instance using module.exports and require() it wherever needed.


Share Now :
Share

⚙️ Node.js – MySQL Get Started

Or Copy Link

CONTENTS
Scroll to Top