express js with mysql code example
Example 1: how to manage a db connection in javascript
const mysql = require('mysql2');
const connection = mysql.createPool({
host: "localhost",
user: "",
password: "",
database: ""
});
module.exports = connection;
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: how to access a database in express
var MongoClient = require('mongodb').MongoClient
MongoClient.connect('mongodb://localhost:27017/animals', function (err, client) {
if (err) throw err
var db = client.db('animals')
db.collection('mammals').find().toArray(function (err, result) {
if (err) throw err
console.log(result)
})
})
Example 3: how to access a database in express
var mysql = require('mysql')
var connection = mysql.createConnection({
host: 'localhost',
user: 'dbuser',
password: 's3kreee7',
database: 'my_db'
})
connection.connect()
connection.query('SELECT 1 + 1 AS solution', function (err, rows, fields) {
if (err) throw err
console.log('The solution is: ', rows[0].solution)
})
connection.end()