How to Handle MySQL Connection Errors in NodeJS?
Last Updated :
03 Sep, 2024
Dealing with MySQL connection errors requires you to look at issues related to establishing, maintaining, and closing connections to the MySQL database. This includes initial connection failure, connection drop detection and recovery, and error handling during query execution. Effective error handling ensures that your application remains stable and functional.
Creating NodeJS Application
Step 1: Install NodeJS
First, you need to install Node.js. You can download it from the official Node.js website.
Step 2: Set Up Your Project
Create a new directory for your project and navigate into it:
mkdir my-node-app
cd my-node-app
Step 3: Initialize a new Node.js project:
npm init -y
Step 4: Create Your Application
- Create a new file named app.js
app.js
- Open app.js in your favorite code editor and add the following code to create a simple web server
JavaScript
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Steps to connect Mysql
- Install the MySQL package
npm install mysql
- Add the following code to connect to a MySQL database
const mysql = require('mysql');
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "my_db"
});
connection.connect((err) => {
if (err) {
console.error('Error connecting: ' + err.stack);
return;
}
console.log('Connected as id ' + connection.threadId);
});
Project structure:
Project StructureUpdated dependencies:
"dependencies": {
"mysql": "^2.18.1"
}
Example: This example shows the handling error.
JavaScript
const mysql = require('mysql');
// Create a connection to the database
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydatabase'
});
// Attempt to connect to the database
connection.connect((err) => {
if (err) {
console.error('Error connecting to the database:', err.message);
return;
}
console.log('Connected to the MySQL server.');
});
// Handle errors after the initial connection
connection.on('error', (err) => {
console.error('Database error:', err.message);
// Handle connection lost error
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
console.error('Connection lost. Reconnecting...');
connection.connect();
} else {
throw err;
}
});
// Close the connection
connection.end((err) => {
if (err) {
console.error('Error closing the connection:', err.message);
return;
}
console.log('Connection closed.');
});
Steps to Run the Code:
node app.js
Output:
Output
Similar Reads
How to Handle Errors in Node.js ? Node.js is a JavaScript extension used for server-side scripting. Error handling is a mandatory step in application development. A Node.js developer may work with both synchronous and asynchronous functions simultaneously. Handling errors in asynchronous functions is important because their behavior
4 min read
How To Handle Global Connection of MongoDB in NodeJs? Handling a global connection to MongoDB in a Node.js application is important for efficient resource management and performance optimization. By maintaining a single connection to the MongoDB database, you avoid the overhead of repeatedly establishing and closing connections, which can be resource-i
2 min read
How to Handle Lost Connection to Mongodb from Nodejs? Handling lost connections to MongoDB in a Node.js application is crucial for maintaining application reliability and data integrity. However, network issues, database server crashes, or other unexpected events can cause the connection to be lost. This article will guide you through different approac
3 min read
How to Handle Syntax Errors in Node.js ? If there is a syntax error while working with Node.js it occurs when the code you have written violates the rules of the programming language you are using. In the case of Node.js, a syntax error might occur if you have mistyped a keyword, or if you have forgotten to close a parenthesis or curly bra
4 min read
How to Handle Errors for Async Code in Node.js ? Handling errors effectively in asynchronous code is crucial for building robust and reliable Node.js applications. As Node.js operates asynchronously by default, understanding how to manage errors in such an environment can save you from unexpected crashes and ensure a smooth user experience. This a
4 min read
How to use .env file in NodeJS MySQL? Environment variables are list of properties defined by key and value used for storing configurations data for instance the database credentials, api keys and so on. In the past, these values were directly coded into your applicationsâ code and were not flexible to change, but today we can store the
4 min read