Mysql with Nodejs: insertion of records

Asked

Viewed 1,155 times

2

I created a script called 'test.js" just to demonstrate a simple insertion of log records into a Mysql database, using Nodejs, as follows. Will be generated around 5 logs per second, which makes me assume that will require a certain machine processing to run this my script every log generated. My question is: is there a way to leave a connection open so that log records are inserted, without the need to keep opening and closing the connection to each log? Or I don’t know... if there is a more appropriate way totally different, I would like to know any alternative.

const mysql = require('mysql');

const con = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'meu_db_teste'
});

con.connect((err) => {
    if(err){
        console.log('Erro de conexão do DB');
        return;
    }
    console.log('Conexão estabilizada com threadId: ', con.threadId);
});

// Estes dados do "reg_log" virão de um outro script
const reg_log = { info: 'abcde...xyz', dttime: 'xx:xx:xx' };
con.query('INSERT INTO logs SET ?', reg_log, (err, res, fields) => {
    if(err) throw err;

    console.log('Last insert ID:', res.insertId);
});

con.end((err) => {
    console.log('Connection closed');
});

2 answers

1

The ideal scenario is to separate the database connection file to implement some kind of Singleton, something like that:

Connection.js

const mysql = require('mysql');
var single_connection;
module.exports = function() {
    if (!single_connection) {
        single_connection = mysql.createConnection({
            host: 'localhost',
            user: 'root',
            password: '123456',
            database: 'meu_db_teste'
        });
    }
    return single_connection;
}

js test.

const db = require('connection);
...
  • Lucas, grateful for the return, for me it is clear the intention to separate the part of the connection in an independent file, but just to understand: I will have a script of my own, which will be monitoring a certain condition of the system. Each time this condition is true, I call my script to create a record in the database and in this my script there will be your const db = require('connection);, ok! That’s not the same thing I’m doing there in my example, only in my example is no separate files?

  • Actually no, require is Singleton and the difference is that if there is already a connection with the database, it will only return when the files are run.

  • and in this case it is not necessary to terminate the connection? Because I suppose it will give timeout that open connection for a long time... If yes, when will I close?

  • The connection I usually leave one open during the @wBB application lifecycle, and manage the pull of connections

  • Ok. I’ll try here to see what happens. There is still a part to implement to run a test closer to the actual situation. Thank you!

0

dbconnection file:

var mysql = require('mysql');

var connMysql = () => {
    return mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: '1234',
        database: 'banco'
    });
}

module.exports = () => {
    console.log('Conexao estabelecida com banco de dados');
    return connMysql;
}

using models:

function NoticiasDao(connection) {
    this._connection = connection;
}


NoticiasDao.prototype.getNoticias =  function(callback){
    this._connection.query('select * from noticias', callback);
}


NoticiasDao.prototype.getNoticia = function(callback) {
    this._connection.query('select * from noticias where idNoticias = 2', callback);
}


NoticiasDao.prototype.salvarNoticia = function(noticia, callback) {
    this._connection.query('insert into noticias set ?', noticia, callback);
}



module.exports = function() {

    return NoticiasDao;
}

Controller :

module.exports.formulario = function(app, req, res) {
    response.render("admin/form_add_noticia", { validation: '',noticia:noticia});
}

module.exports.salvarNoticia = function(app, req, res) {
    var noticia = request.body;
    var connection = app.config.dbconnection();
    var noticiaDao = new app.app.models.NoticiasDao(connection);


            noticiaDao.salvarNoticia(noticia, function(error, result) {
                response.redirect('/noticias');
            });

    });
}

using consign you initialize connection , models, controller on start server

var consign = require('consign');
consign()
    .include('app/routes')
    .then('config/dbconnection.js')
    .then('app/models')
    .then('app/controllers')
    .into(app);
  • Eduardo, I’m grateful for the return, but I’m a beginner in Nodejs and I’m struggling to understand how things really work. I don’t even know how to use your example and I’d like to understand how this way of inserting records slows down machine processing.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.