Step 6: Connection with the Database**
In this step, we explore how to establish a connection between our Node.js application and a MySQL database to efficiently persist data. You will learn to:
This step is essential to optimize the performance of the application, avoiding continuous readings from files in Google Drive and allowing more efficient analysis of the stored data. ?
This code establishes a connection to a MySQL database using mysql2 and handles connection errors and queries using promises. Each part of the process is detailed below to document its use.
Environment Requirements and Configuration:
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
Creation of the Connection Pool:
const pool = mysql.createPool(localhost);
Promisification of Queries:
pool.query = promisify(pool.query);
Error Management:
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}`); } });
Requirements and Configuration:
Pool Creation:
Promisification:
Error Management:
This code is useful for connecting Node.js applications with MySQL databases, providing a robust solution for connection and error management using modern techniques such as promisification and proper exception handling.
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
The above is the detailed content of Thread Continuation: How to Create a Personal Finance Application Integrating Google Drive, MySQL and Node.js. For more information, please follow other related articles on the PHP Chinese website!