xxxxxxxxxx
//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;
Connecting to a SQL database using Node.js and the mysql package:
xxxxxxxxxx
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'username',
password: 'password',
database: 'databasename'
});
connection.connect((err) => {
if (err) {
console.error('Error connecting to database:', err);
return;
}
console.log('Connected to database');
});