Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
630 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 Reply

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'); });
    });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...