inside MysqlSingleTon.js
const mysql = require('mysql');
class MysqlConnection {
    constructor() {
        this.connection = mysql.createConnection({
            host: 'localhost',
            user: 'root',
            password: 'sangram#81',
            database: 'playground'
        });
        this.connection.connect((err) => {
            if (err) {
                console.error('Error connecting to MySQL:', err);
                return;
            }
            console.log('Connected to MySQL');
        });
    }
    query(sql, values) {
        return new Promise((resolve, reject) => {
            this.connection.query(sql, values, (err, results) => {
                if (err) {
                    reject(err);
                    return;
                }
                resolve(results);
            });
        });
    }
    close() {
        return new Promise((resolve, reject) => {
            this.connection.end((err) => {
                if (err) {
                    console.error('Error closing MySQL connection:', err);
                    reject(err);
                    return;
                }
                console.log('MySQL connection closed');
                resolve();
            });
        });
    }
}
class MySQLSingleton {
    constructor() {
        if (!MySQLSingleton.instance) {
            MySQLSingleton.instance = new MysqlConnection()
        }
    }
    getInstance() {
        return MySQLSingleton.instance
    }
}
const instance = new MySQLSingleton();
Object.freeze(instance);
module.exports = instance;
consuming class created
const instance = require('./MysqlSingleTon')
const connection = instance.getInstance()
connection.query("SELECT * FROM emp;")
    .then((result) => {
        console.log(result);
    })
    .catch((error) => {
        console.error(error);
    })
    .finally(() => {
        connection.close()
            .catch((error) => {
                console.error(error);
            });
    });
 
No comments:
Post a Comment