Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

android - JSON data insert sqLit Database not working

I tried to JSON data insert into SqLit database in PhoneGap. I created a table with two columns, like this:

function setup(tx) {

    tx.executeSql('DROP TABLE IF EXISTS HEADER_DATA');
    tx.executeSql("create table if not exists bookinformation(inserkey TEXT, key TEXT)");
}

This code runs successfully and the table is created. Then, I insert JSON data into the bookinformation table, like this:

function dbReady() {
db.transaction(function(tx) {
        alert("5");
        $.getJSON('http://echo.jsontest.com/key/value/one/two',function(data){
         $.each(data, function(i, dat){
         tx.executeSql('INSERT OR REPLACE INTO bookinformation (inserkey, key) VALUES("'+data.one+'", "'+data.key+'")');    
        alert("completed");
    });
});     
    }, errorHandler, function() { alert('added row'); });
}

However, the insert statement fails. I get this error:

Uncaught InvalidStateError:Failed to execute 'executeSql' on 'SQLTransaction':SQL execution is disallowed

What is causing this error?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Old question but this might help others.

That error is usually caused by the transaction tx being stale.

This is because of the ajax call and by the time your ajax callback gets hit that tx object is no longer valid. The same happens if you use setTimeout or any time consuming non-Websql operation aswell.

To avoid that simply, create the transaction inside in the callback.

E.g

function dbReady() {
    $.getJSON('http://echo.jsontest.com/key/value/one/two',function(data) {
        db.transaction(function(tx) {
            alert("5");
            $.each(data, function(i, dat) {
                tx.executeSql('INSERT OR REPLACE INTO bookinformation (inserkey, key) VALUES("'+data.one+'", "'+data.key+'")');
            });
            alert("completed");
        }, errorHandler, function() { alert('added row'); });
    });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...