How to Handle MySQL Connection Errors in NodeJS?
Last Updated :
03 Sep, 2024
Improve
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
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:
Updated dependencies:
"dependencies": {
"mysql": "^2.18.1"
}
Example: This example shows the handling error.
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:
