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');
});
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?– wBB
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.– BrTkCa
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?
– wBB
The connection I usually leave one open during the @wBB application lifecycle, and manage the pull of connections
– BrTkCa
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!
– wBB