๐Ÿ”— MySQL with Node.js โ€“ Integration Guide with Code Explanations


๐Ÿงฒ Introduction โ€“ Why Use MySQL with Node.js?

Node.js is a powerful asynchronous runtime that excels at building scalable network applications. Combining it with MySQL gives you the ability to store, retrieve, and manage data efficiently for web applications, APIs, and microservices.

๐ŸŽฏ What Youโ€™ll Learn:

  • How to set up MySQL in a Node.js project
  • Perform CRUD operations using mysql2 library
  • Use async/await for non-blocking code
  • Secure your queries with prepared statements
  • Apply best practices for real-world apps

๐Ÿงฐ Setup โ€“ Installing Required Modules

Install MySQL client for Node.js:

npm install mysql2

If you’re using promises or async/await (recommended):

npm install mysql2

โš™๏ธ Connecting Node.js to MySQL

โœ… Basic MySQL Connection

const mysql = require('mysql2');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'your_username',
  password: 'your_password',
  database: 'your_database'
});

connection.connect(err => {
  if (err) {
    console.error('โŒ Connection error:', err.message);
    return;
  }
  console.log('โœ… Connected to MySQL');
});

๐Ÿง  Explanation:

  • mysql.createConnection(): Initializes connection config.
  • connect(): Opens connection to MySQL server.
  • Handles errors gracefully with a callback.

๐Ÿ” CRUD Operations in Node.js + MySQL


๐Ÿ” SELECT โ€“ Retrieving Data

connection.query(
  'SELECT * FROM users WHERE country = ?',
  ['India'],
  (err, results) => {
    if (err) throw err;
    console.log(results);
  }
);

๐Ÿง  Explanation:

  • Uses prepared statements (?) to avoid SQL injection.
  • results contains array of matching rows.

โž• INSERT โ€“ Adding Records

const user = { name: 'John Doe', email: 'john@example.com' };
connection.query(
  'INSERT INTO users (name, email) VALUES (?, ?)',
  [user.name, user.email],
  (err, results) => {
    if (err) throw err;
    console.log('Inserted ID:', results.insertId);
  }
);

๐Ÿง  Explanation:

  • Uses placeholder ? for secure inputs.
  • results.insertId gives you the new row ID.

๐Ÿ“ UPDATE โ€“ Modifying Records

connection.query(
  'UPDATE users SET email = ? WHERE id = ?',
  ['john.updated@example.com', 1],
  (err, results) => {
    if (err) throw err;
    console.log(`Rows updated: ${results.affectedRows}`);
  }
);

๐Ÿง  Explanation:

  • Updates email where id = 1.
  • affectedRows tells how many rows were updated.

โŒ DELETE โ€“ Removing Records

connection.query(
  'DELETE FROM users WHERE id = ?',
  [1],
  (err, results) => {
    if (err) throw err;
    console.log(`Rows deleted: ${results.affectedRows}`);
  }
);

๐Ÿง  Explanation:

  • Deletes user with ID = 1.
  • Checks if delete was successful.

โšก Using Async/Await with Promises

Switch to promise-based API:

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

async function run() {
  const conn = await mysql.createConnection({
    host: 'localhost',
    user: 'user',
    password: 'password',
    database: 'mydb'
  });

  const [rows] = await conn.execute('SELECT * FROM users WHERE country = ?', ['USA']);
  console.log(rows);
}

run().catch(console.error);

๐Ÿง  Explanation:

  • Uses mysql2/promise for clean async/await code.
  • conn.execute() replaces query() for promises.

๐Ÿ“˜ Best Practices for Node.js + MySQL

๐Ÿ’ก Use Connection Pooling:

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

๐Ÿ” Prevent SQL Injection:

  • Always use ? placeholders.
  • Never concatenate user input into SQL strings.

โš™๏ธ Use .env to Manage Configs:

DB_HOST=localhost
DB_USER=root
DB_PASS=secret

Then in Node.js:

require('dotenv').config();
const connection = mysql.createConnection({
  host: process.env.DB_HOST,
  ...
});

๐Ÿ“Š Real-World Use Cases

Application TypeMySQL + Node.js Role
RESTful APIsUser auth, CRUD routes
Admin DashboardsData visualizations, filters, pagination
E-commerce BackendOrders, products, inventory management
IoT SystemsSensor data logging
Messaging SystemsChat and notification history

๐Ÿ“Œ Summary โ€“ Recap & Next Steps

๐Ÿ” Key Takeaways

  • Use mysql2 for secure and fast integration
  • Prefer async/await with mysql2/promise
  • Secure inputs with placeholders
  • Store configs outside code using .env

โš™๏ธ Real-World Relevance
Node.js with MySQL is ideal for building modern web apps and microservices. Whether you’re building APIs or dashboards, this combo offers speed, scalability, and reliability.


โ“ FAQ โ€“ Node.js MySQL Integration

โ“ Whatโ€™s the difference between mysql and mysql2?
โœ… mysql2 is a faster, improved version that supports promises and modern syntax.

โ“ Can I use MySQL with Express.js?
โœ… Yes. You can call query() or execute() inside your route handlers.

โ“ How to prevent SQL injection in Node.js?
โœ… Always use parameterized queries (placeholders ?) instead of string concatenation.

โ“ Which is better: Raw SQL or ORM?
โœ… For flexibility and performance, raw SQL is great. For complex systems, ORMs like Sequelize may simplify development.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

๐Ÿ”— MySQL with Node.js

Or Copy Link

CONTENTS
Scroll to Top