Database Integration

  • Database integration in Node.js involves connecting the application to a database to store, retrieve, and manage data.

  • This process is essential for creating dynamic applications that interact with data.

1. Choosing a Database

  • SQL Databases: Such as PostgreSQL and MySQL, use structured query language (SQL) for defining and manipulating data.

  • NoSQL Databases: Such as MongoDB and CouchDB, are designed for unstructured data and offer flexible schemas.

2. Connecting to a Database

For SQL Databases: Use libraries like pg for PostgreSQL or mysql2 for MySQL.

3. Performing CRUD Operations

  • Create: Insert new data into the database

  • Read: Query data from the database.

  • Update: Modify existing data.

  • Delete: Remove data from the database.


MySQL Database Setup

To integrate a MySQL database with Node.js application, you need to configure a connection pool, handle queries, and ensure proper table creation.

Setting Up the Database Connection

Use the mysql2/promise library to create a connection pool that allows efficient handling of multiple database connections.

Database Connection Configuration:

mysql.createPool(): Creates a pool of connections to the MySQL database.

connectionLimit: Specifies the maximum number of connections in the pool.

Query Execution Utility

Create a utility function for executing SQL queries. This function handles acquiring and releasing connections automatically.

Query Execution Function:

pool.getConnection(): Obtains a connection from the pool.

connection.query(): Executes the SQL query.

connection.release(): Releases the connection back to the pool.

Recipe Controller Functions

Implement controller functions for managing recipe data. These functions interact with the database using the query utility.

Recipe Controller Example:

Table Creation Script

Create the necessary database table using a script that ensures the table is created if it doesn’t already exist.

Table Creation Script:

Table Definition:

id: Auto-increment primary key.

name: Non-nullable field for the recipe name

description: Optional field for additional details.

created_at & updated_at: Timestamps for record creation and last update.

This section demonstrates how to integrate MySQL with a Node.js application by configuring a connection pool, executing queries, and managing recipe data.

Last updated