Tue Aug 01 2023

MySQL Connection

Node JS220 views
MySQL Connection

File Name: mysql-nodejs-connection.js

const mysql = require('mysql');

const con = new mysql.createConnection({
    host : 'localhost',
    user : 'root',
    password : 'Qwerty@2022',
    database : 'testing'
});

const connectDB = async () => {
    con.connect(function (err) {
        if(err) {
            console.error('Error connecting to database: ', err.stack);
            process.exit(1);
        }
        console.log('Connection established with ID: ', con.threadId);
        return con;
    });
}

const endConnection = async () => {
    con.end((err) => {
        if(err) {
            console.error('Error while closing connection: ', err.stack);
            process.exit(1);
        }
        console.log('Connection Closed Successfully!');
        return con;
    });
}

module.exports = {connectDB, endConnection};

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.