WikiGalaxy

Personalize

Using MySQL with Node.js

Introduction to MySQL and Node.js:

Node.js is a popular JavaScript runtime built on Chrome's V8 engine, known for its non-blocking, event-driven architecture. MySQL is a widely-used open-source relational database management system. Combining MySQL with Node.js allows developers to create robust and scalable web applications.

Setting Up MySQL with Node.js:

To use MySQL in Node.js, you need to install the MySQL driver. The most common package is mysql, which provides a simple API to interact with MySQL databases.

Basic Operations (CRUD):

CRUD operations (Create, Read, Update, Delete) are fundamental when working with databases. Node.js provides various methods to perform these operations efficiently using MySQL.

Connection Handling:

Managing database connections efficiently is crucial for application performance. Node.js allows you to create a connection pool to handle multiple requests simultaneously.

Security Considerations:

Security is paramount when dealing with databases. Node.js applications should implement measures like input validation, parameterized queries, and secure connection protocols to protect data integrity.

Install MySQL Package

Installing MySQL Package:

To begin using MySQL in your Node.js application, you need to install the MySQL package via npm. This package provides the necessary tools to connect and interact with a MySQL database.


npm install mysql
        

Why Install MySQL Package?

Installing the MySQL package is essential as it provides an API for Node.js to communicate with the MySQL database. This package simplifies database connections and queries.

Connecting to MySQL Database

Establishing a Connection:

To interact with a MySQL database, you first need to establish a connection. This involves specifying the host, user, password, and database name.


const mysql = require('mysql');
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'testdb'
});
connection.connect((err) => {
    if (err) throw err;
    console.log('Connected to MySQL!');
});
        

Connection Explanation:

The above code snippet demonstrates how to establish a connection to a MySQL database using the mysql package. It connects to a database named 'testdb' on the local server.

Performing CRUD Operations

Creating Records:

The INSERT statement is used to create new records in a table. Below is an example of how to insert a record into a MySQL database using Node.js.


const sql = 'INSERT INTO users (name, age) VALUES (?, ?)';
connection.query(sql, ['John Doe', 30], (err, result) => {
    if (err) throw err;
    console.log('Record inserted:', result.insertId);
});
        

Explanation of INSERT:

This code inserts a new record into the 'users' table. The query method executes the SQL statement with the provided data, and the result.insertId returns the ID of the inserted record.

Reading Records

Querying Data:

To read data from a MySQL database, you use the SELECT statement. Below is an example of how to fetch records from a table.


const sql = 'SELECT * FROM users';
connection.query(sql, (err, results) => {
    if (err) throw err;
    console.log('Data received:', results);
});
        

Explanation of SELECT:

The SELECT statement is used to fetch all records from the 'users' table. The results are returned as an array of objects, each representing a row in the table.

Updating Records

Modifying Data:

To update existing records in a database, the UPDATE statement is used. Below is an example of how to update a record in a MySQL database using Node.js.


const sql = 'UPDATE users SET age = ? WHERE name = ?';
connection.query(sql, [35, 'John Doe'], (err, result) => {
    if (err) throw err;
    console.log('Record updated:', result.affectedRows);
});
        

Explanation of UPDATE:

This code updates the age of 'John Doe' to 35 in the 'users' table. The affectedRows property indicates how many rows were affected by the update operation.

Deleting Records

Removing Data:

To delete records from a database, the DELETE statement is used. Below is an example of how to delete a record in a MySQL database using Node.js.


const sql = 'DELETE FROM users WHERE name = ?';
connection.query(sql, ['John Doe'], (err, result) => {
    if (err) throw err;
    console.log('Record deleted:', result.affectedRows);
});
        

Explanation of DELETE:

This code deletes the record of 'John Doe' from the 'users' table. The affectedRows property shows how many rows were deleted by the operation.

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025