0
0
Node.jsframework~5 mins

MySQL connection with mysql2 in Node.js

Choose your learning style9 modes available
Introduction

We use mysql2 to connect Node.js apps to MySQL databases. It helps us send queries and get data easily.

You want to save or get data from a MySQL database in your Node.js app.
You need to run SQL queries from your server code.
You want to build a web app that stores user info in MySQL.
You want to fetch data from MySQL and show it on a website.
You want to update or delete records in a MySQL database from Node.js.
Syntax
Node.js
import mysql from 'mysql2';

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'yourUsername',
  password: 'yourPassword',
  database: 'yourDatabase'
});

connection.connect(error => {
  if (error) {
    console.error('Connection failed:', error);
    return;
  }
  console.log('Connected to MySQL!');
});

Replace host, user, password, and database with your MySQL info.

Always handle connection errors to avoid crashes.

Examples
Basic connection example with common settings.
Node.js
import mysql from 'mysql2';

// Simple connection
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '1234',
  database: 'testdb'
});

connection.connect(err => {
  if (err) throw err;
  console.log('Connected!');
});
This example shows how to create a pool with promises for easier async code.
Node.js
import mysql from 'mysql2';

// Using promise wrapper for async/await
const promisePool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: '1234',
  database: 'testdb'
}).promise();
Sample Program

This program connects to MySQL, runs a simple query to get the current time, prints it, then closes the connection.

Node.js
import mysql from 'mysql2';

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '1234',
  database: 'testdb'
});

connection.connect(error => {
  if (error) {
    console.error('Connection failed:', error);
    return;
  }
  console.log('Connected to MySQL!');

  connection.query('SELECT NOW() AS currentTime', (err, results) => {
    if (err) {
      console.error('Query error:', err);
    } else {
      console.log('Current time from MySQL:', results[0].currentTime);
    }
    connection.end();
  });
});
OutputSuccess
Important Notes

Use connection.end() to close the connection when done.

For many queries, consider using connection pools for better performance.

Keep your database credentials safe and do not hardcode them in production.

Summary

mysql2 lets Node.js talk to MySQL databases easily.

Set up connection with your database info and handle errors.

Run queries and close connections properly to keep your app stable.