Answer the question
In order to leave comments, you need to log in
How to correctly organize a query to a MySQL database from a Node.JS application?
Hello comrades! Please help me figure it out. I'm trying to correctly organize a query to a MySQL database from a Node.JS application.
In a Node.JS project, the first time I start the server, I call a module that creates a pool for the MySQL database. This module looks like this:
const mysql = require('mysql');
const configuration = require('../config/mysql_database');
async function initialization() {
await mysql.createPool(configuration);
}
module.exports.initialization = initialization;
function executeSQLStatement(query, binds = []) {
return new Promise(async (resolve, reject) => {
let connection;
try {
const result = await mysql.query(query, binds, function (error, results, fields) {
if (error) throw error;
});
resolve(result);
} catch (error) {
reject(error);
} finally {
if (connection) {
try {
await connection.close();
} catch (error) {
console.log(error);
}
}
}
});
}
module.exports.executeSQLStatement = executeSQLStatement;
TypeError: mysql.query is not a function
at new Promise (<anonymous>)
500 at Object.executeSQLStatement
Answer the question
In order to leave comments, you need to log in
This can be placed in a separate file.
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'example.org',
user : 'bob',
password : 'secret',
database : 'my_db'
});
module.exports = pool;
const pool = require('./file');
const query = 'SELECT 1 + 1 AS solution';
const result = await pool.query(query);
From the official documentation, it can be seen that when a request is executed, a pool is created each time.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question