Sqlite with Javascript does not work

Asked

Viewed 748 times

4

I am knowing the Sqlite now, to try to deploy in a mobile application, I made this test based on some web codes but I can not return a recording of the data successfully, until it selects but returns 0 records, as shown in the excerpt: alert(r.rows.length);

var db = openDatabase("appLocal", "1.0", "base de dados da aplicacao", 

200000);

// criando a tabela caso ela não exista
db.transaction(function(transaction){
    transaction.executeSql('CREATE TABLE IF NOT EXISTS tb_teste ("teste" TEXT)', [], null, db.onError);
    alert("criou");
});

// aqui vai o insert
db.transaction(function(transaction){    
  transaction.executeSql("INSERT INTO tb_teste(teste) VALUES('testex');", db.onSuccess, db.onError);
    alert("inseriu");
});

// consulta no banco
db.transaction(function(transaction){
    transaction.executeSql("SELECT * FROM tb_teste", [], db.getResults, db.onError);
    alert("selecionou");
});

// função callback de erro
db.onError = function(transaction, e) {
  alert("Aconteceu um erro!");
  console.log(e.message);
}

// função de callback de sucesso de insert
db.onSuccess = function(transaction, e) {
  alert("Dados Gravados com Sucesso!");
  console.log(e);
}

// função temporaria que lista resultados
db.getResults = function (transaction, r) {
    //console.log('deu certo!');
    //console.log(r);
    alert(r.rows.length);

   for(var i = 0; i < r.rows.length; i++){
       alert(r.rows.item(i)[['teste']]);
       alert("rodou");
   }
}

1 answer

2

The problem is happening in function call transaction.executeSql to insert data into the table.

This function does not accept parameters of callback for error or success (tested in Google Chrome, but for other browsers, may work differently).

The command line to do INSERT should look like this:

transaction.executeSql("INSERT INTO tb_teste(teste) VALUES('testex');")

or so:

transaction.executeSql("INSERT INTO tb_teste(teste) VALUES(?);", ['testex']);


See working on jsfiddle


A tip:

According to the documentation Web SQL Database - W3C, this API (Sqlite) is obsolete and its use is not recommended.

To store data in the customer, you can use:

Browser other questions tagged

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