javascript sql database connection example

Example 1: 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;

Example 2: js access sql database on server

// Use JSMYSQLDB to read tables from a database on the server (not write)
// -> https://github.com/JackChilds/jsmysqldb
// For full disclosure, I built the tool.