Tue Aug 01 2023
MySQL Connection
Node JS220 views
![MySQL Connection](/_next/image?url=https%3A%2F%2Fcdn.geekboots.com%2Fgeek%2Fnodejs-connect-with-mysql-vidImg-1691482872468.webp&w=3840&q=75)
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};
Author:Geekboots