Doubt in Javascript + Sqlite3, return of Select

Asked

Viewed 132 times

0

Hello, I need to retrieve information from a bank and display on a table. I’m using Electron and sqlite3. I have this function to do the consultation.

function getTable(){
  var obj = [];
  var aux = [];
  db.each('SELECT nome, categoria, grau FROM receita', function(err, row) {
    aux.push(row.nome);
    aux.push(row.categoria);
    aux.push(row.grau);
    obj.push(aux);
    aux = [];
  });
  return(obj);
}

After I do the query I want to return the array of elements, but it returns an empty array, but if I use the console.log I can see the elements, I just can’t access them, when I try to access it says it is empty. I am using jquery.Datatable and with it vc declares the table in html and js vc calls it so:

var obj = getTable();
$(document).ready(function() {
  $('#receitaTable').DataTable( {
    data: obj,
    columns: [
      { title: "Nome" },
      { title: "Categoria" },
      { title: "Grau" }
    ]
    }); 
});

However the query of my select does not let me "take the elements out", I can use if everything is within db.each('SELECT name, category, grade FROM recipe', Function(err, Row) {.... However, if I use the datatable inside db.each... it has an error, as it will create the table several times.

SUMMING UP: I wanted to know how I do the query and get the saved element in a variable, which even if I give db.close, the element is saved in the variable.

Thanks in advance.

1 answer

0

Only playing the values in the array will not have allow you to group each row that returns from the bank, and read with the names you need (Name, Category, etc). You need to create an object and add an object that represents an "Row", like this:

db.each('SELECT nome, categoria, grau FROM receita', function(err, row) {
    var obj= {
       "Nome": row.nome,
       "Categoria": row.categoria,
       "Grau": row.grau
    };

    aux.push(obj);
  });

Thus clearer what is inside your object, an array of objects with attributes "Name", "Category" and "Degree".

Browser other questions tagged

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