</>
Skip to content
Node.js lessons (39/44)

Node.js — MySQL

Installation

npm install mysql2

Connection

const mysql = require('mysql2/promise');

const pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'mydb',
    waitForConnections: true,
    connectionLimit: 10
});

Querying

// Simple query
const [rows] = await pool.execute('SELECT * FROM users');

// Parameterized query
const [rows] = await pool.execute(
    'SELECT * FROM users WHERE id = ?',
    [userId]
);

// Insert
await pool.execute(
    'INSERT INTO users (name, email) VALUES (?, ?)',
    ['John', 'john@example.com']
);

CRUD Operations

// Read
const [users] = await pool.execute('SELECT * FROM users');

// Create
await pool.execute(
    'INSERT INTO users (name, email) VALUES (?, ?)',
    [name, email]
);

// Update
await pool.execute(
    'UPDATE users SET name = ? WHERE id = ?',
    [name, id]
);

// Delete
await pool.execute('DELETE FROM users WHERE id = ?', [id]);

Error Handling

try {
    const [rows] = await pool.execute('SELECT * FROM users');
} catch (err) {
    console.error('Database error:', err.message);
}

Mini Practice

  1. Set up MySQL connection pool
  2. Perform CRUD operations
  3. Use parameterized queries
  4. Handle database errors

Up Next

Continue with MongoDB — MongoDB integration.

Related Topics

Frequently Asked Questions about MySQL

What is MySQL in Node.js?

MySQL is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn MySQL?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn MySQL.

Why is MySQL important in Node.js?

MySQL is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.