Node Js Database Connection Best Practice Code Example


Example: how to manage a db connection in javascript


//put these lines in a seperate file
const mysql = require('mysql2');

const connection = mysql.createPool(
{
host: "localhost",
user: "",
password: "",
database: ""
// here you can set connection limits and so on
});

module.exports = connection;

//put these on destination page
const connection = require('../util/connection');

async function getAll()
{
const sql = "SELECT * FROM tableName";
const [rows] = await connection.promise().query(sql);
return rows;
}
exports.getAll = getAll;

Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable