Step 6: Connect to the database**
In this step, we will explore how to establish a connection between a Node.js application and a MySQL database to save data efficiently. You will learn:
- Set database credentials in Node.js.
- Use the library
mysql2
to manage connections. - Build basic queries to insert, update, and retrieve data.
This step is essential to optimize the performance of the application, avoid continuously reading files in Google Drive, and allow for more efficient analysis of stored data. 🚀
MySQL connection database code documentation in Node.js
This code uses the following command to establish a connection to the MySQL database mysql2 And use promises to handle connection errors and queries. Each part of the process is detailed below to document its use.
Code settings
-
Environmental requirements and configuration:
- Need packaging
mysql2
Interact with MySQL database. - it is used
dotenv
Manage environment variables, allowing for secure configuration of sensitive information such as database credentials. - Connection settings are obtained from the configuration file or environment variables (if used)
dotenv
.
const mysql = require('mysql2'); const { promisify } = require('util'); require('dotenv').config(); // Cargar variables de entorno const localhost = process.env.DATABASE_CONFIG || require('../config'); // Recuperar configuración desde dotenv o archivo de configuración
- Need packaging
-
Creation of connection pool:
- Create a connection pool using the restored configuration. This helps maintain persistent and reusable connections, optimizing performance.
const pool = mysql.createPool(localhost);
-
query commitment:
- The query was promised using asynchronous processing
promisify
. This simplifies the management of query results and errors.
pool.query = promisify(pool.query);
- The query was promised using asynchronous processing
-
Error management:
- Handle possible wiring errors and queries. For example, special handling of errors such as access denied, connection lost, or maximum number of connections reached.
pool.getConnection() .then(connection => { connection.release(); console.log("Conexión establecida correctamente."); }) .catch(err => { if (err.code === 'ER_NOT_SUPPORTED_AUTH_MODE' || err.code === 'ER_ACCESS_DENIED_ERROR') { console.error('Error de acceso denegado. Revise las credenciales.'); } else if (err.code === 'PROTOCOL_CONNECTION_LOST') { console.error('La conexión con la base de datos se perdió.'); } else if (err.code === 'ER_CON_COUNT_ERROR') { console.error('Demasiadas conexiones activas.'); } else if (err.code === 'ECONNREFUSED') { console.error('La conexión con la base de datos fue rechazada.'); } else { console.error(`Error desconocido: ${err.message}`); } });
Detailed explanation of the program code
-
Requirements and Configuration:
-
mysql2
Provides an API for interacting with MySQL. -
dotenv
It is used to manage configuration through files.env
Or direct environment variables. -
localhost
Contains database configuration data, such as host, user, password, etc.
-
-
Create a pool:
-
mysql.createPool(localhost)
Creates a persistent connection, which is ideal for applications that handle multiple connections simultaneously.
-
-
promise:
- SQL queries are allowed to be used as asynchronous functions, which makes them easier to handle in modern applications.
-
Error management:
- Common errors such as connection lost, access denied, or query denied are carefully handled to provide developers with useful information and avoid crashes.
Use in projects
This code is useful for connecting Node.js applications to MySQL databases, providing a powerful solution for connection and error management using modern techniques such as promiseization and proper exception handling.