N
N
NeTLeaDeR2019-04-16 22:03:40
Node.js
NeTLeaDeR, 2019-04-16 22:03:40

How to correctly form queries to the database?

Hello. I started to get acquainted with node js, I decided to write a small program, but I ran into difficulties.
1) I don’t know where to close the connection (and whether it is necessary to close it at all in my case)
2) If the number of records in the database is small, then everything works fine (screenshot), and if it is large, then it simply refuses to start.
Actually the question itself: how to correctly implement these queries to the database?

const mysql = require('mysql');
var connection = mysql.createConnection({
  host     : 'host',
  user     : 'user',
  password : 'password',
  database : 'database'
});

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
    connection.connect();
    
    var timerId = setInterval(function() {
        connection.query('SELECT * FROM nodetest WHERE used = 0', function(error, result){
            if (error) throw error;

            var i = 0;
            while (result[i] !== undefined) {
                connection.query('UPDATE nodetest SET used = ? WHERE id = ?', ['1', result[i]['id']], function (err, results) {
                    if (err) throw err;
                    if(results['changedRows'] == 1) console.log('Сообщение отправлено');
                });

                client.channels.get('121231231233').send(result[i]['text']);
                i++;
            }

        });
    }, 10000);  
});

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question