Node.js Tutorial
Estimated reading: 3 minutes 280 views

Node.js โ€“ MySQL: Introduction & Setup โ€“ Connect and Manage Databases with Ease

Introduction โ€“ Why Use MySQL with Node.js?

When building data-driven applications, integrating a relational database like MySQL with Node.js is a powerful choice. MySQL offers structured data storage and advanced querying capabilities, while Node.js provides fast, asynchronous execution for backend APIs.

In this guide, youโ€™ll learn:

  • How to install MySQL and set it up for use with Node.js
  • How to install and use the mysql Node.js driver
  • How to connect Node.js to a MySQL server
  • How to create a database and tables from Node.js

Topics Covered

Topic Description
Node.js โ€“ MySQL Get StartedInstall MySQL and Node.js driver; test database connection
Node.js โ€“ MySQL Create Database / TablesProgrammatically create database and tables using SQL queries

Node.js โ€“ MySQL Get Started

Prerequisites

Make sure you have:

  • Node.js installed (node -v)
  • MySQL server running locally or remotely
  • MySQL root/user credentials

Step 1: Install MySQL Driver

npm install mysql

The mysql package allows Node.js to query and manipulate MySQL databases.


Step 2: Create db.js for Connection

const mysql = require('mysql');

// Create connection
const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '', // change if needed
});

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

module.exports = db;

Output:

Connected to MySQL!

Always wrap connect() in error handling for production setups.


Node.js โ€“ MySQL Create Database / Tables

Step 3: Create Database

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

db.query("CREATE DATABASE companyDB", (err, result) => {
  if (err) throw err;
  console.log("Database created!");
});

Output:

Database created!

Step 4: Connect to the New Database

Update db.js:

const db = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'companyDB'
});

Step 5: Create Table โ€“ Employees

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

const sql = `
  CREATE TABLE employees (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    position VARCHAR(100),
    salary DECIMAL(10,2)
  )
`;

db.query(sql, (err, result) => {
  if (err) throw err;
  console.log("Employees table created!");
});

Output:

Employees table created!

You can run similar queries to define other tables like departments, tasks, etc.


Summary โ€“ Recap & Next Steps

With just a few lines of code, Node.js can connect to a MySQL server and execute queries to create databases and tables. This forms the foundation of full-stack apps that store and retrieve structured data.

Key Takeaways:

  • Use the mysql package to connect Node.js to MySQL
  • Always check connections with proper error handling
  • Create databases and tables programmatically using SQL from Node

Real-World Uses:

  • Backend APIs that interact with MySQL for authentication and CRUD
  • Inventory, finance, and reporting systems
  • Admin dashboards with real-time MySQL data

Frequently Asked Questions

Do I need MySQL installed locally for this to work?
You can use either a local or remote MySQL serverโ€”just update the host and port.


Whatโ€™s the difference between mysql and mysql2 packages?
mysql2 supports Promises and prepared statements. mysql is callback-based.


How do I secure my database credentials?
Use environment variables (dotenv package) and avoid hardcoding credentials in production.


Can I create multiple tables in one file?
Yes, just chain db.query() calls or use a batch SQL string.


Share Now :
Share

๐Ÿ“‚ Node.js โ€“ MySQL: Introduction & Setup

Or Copy Link

CONTENTS
Scroll to Top