N
N
nurzhannogerbek2018-11-23 09:52:52
MySQL
nurzhannogerbek, 2018-11-23 09:52:52

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;

Further in the project, when accessing a specific url address, I launch a controller that calls a function to execute a native SQL query. It looks like this:
mysql_database.js :
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;

Error in terminal:
TypeError: mysql.query is not a function
at new Promise (<anonymous>)
500     at Object.executeSQLStatement

From the official documentation ( link ) it can be seen that when a request is executed, a pool is created each time. How correct is this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene, 2018-11-23
@nurzhannogerbek

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;

And then connect this module and use
const pool   = require('./file');
const query = 'SELECT 1 + 1 AS solution';
const result = await pool.query(query);

M
Michael, 2018-11-23
@mak_ufo

From the official documentation, it can be seen that when a request is executed, a pool is created each time.

Not! The pool is created once , from which a connection is then taken with each request (that's why it is a pool).
The executeSQLStatement function is also not needed, so it is the same as connection.query('', () => {}).
Do everything as in Evgeny's answer, and everything will be fine

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question