从phoneGap从SQlite DB检索值时出错

时间:2011-10-05 10:45:12

标签: javascript sqlite cordova

function populateDB(tx)
{
    tx.executeSql('DROP TABLE IF EXISTS test');
    tx.executeSql('CREATE TABLE IF NOT EXISTS test(course TEXT, grade INTEGER)');
    tx.executeSql('INSERT INTO test(course,grade) VALUES ("Geography, World",90)');
    tx.executeSql('INSERT INTO test(course,grade) VALUES ("Health",92)');
    tx.executeSql('INSERT INTO test(course,grade) VALUES ("Literature, English",91)');
    tx.executeSql('INSERT INTO test(course,grade) VALUES ("Math 201",85)');
    tx.executeSql('INSERT INTO test(course,grade) VALUES ("Science 202",95)');
}

function queryDB(tx)
{
    tx.executeSql('SELECT * FROM test',[],querrySuccess,errorCB);
}

function querrySuccess(tx,results)
{
    var len = results.rows.length;
    alert("test TABLE: "+ len +"row(s) found");
    for(var i=0;i<n;i++)
    {
        console.log("Row = " + i + " COURSE = " + results.rows.item(i).course + " GRADE =  " + results.rows.item(i).grade);
    }
}

function errorCB(err)
{
    alert("Error processing SQL"+err.code);
}

function successCB()
{
    alert("Success!");
}

function create_database()
{
    var db = window.openDatabase("Database","1.0", "Demo DB", 200000);
    db.transaction(populateDB,errorCB,successCB);
    db.transaction(queryDB,errorCB);
}

在上面的代码中,我正在创建一个名为test的新数据库。加载我的html表单时调用函数create_database()。我的问题是,它显示了显示行数的警报,但随后它发出警告“处理SQL错误”,即它被重定向到errorCB函数。是吗?我做错了吗? 提前致谢

3 个答案:

答案 0 :(得分:0)

我会仔细查看您的代码,但首先您的表中没有任何主键。也许你可以测试类似的东西:

"CREATE TABLE IF NOT EXISTS test(ID INTEGER PRIMARY KEY AUTOINCREMENT, course TEXT, grade INTEGER)"

答案 1 :(得分:0)

这是因为db.transaction调用是异步的。您正在尝试从上一个事务之前读取数据库以创建表和插入数据。您应该在第一个完成后触发第二个事务

答案 2 :(得分:0)

use in callback function like this.

tx.executeSql("CREATE TABLE IF NOT EXISTS test(ID INTEGER PRIMARY KEY AUTOINCREMENT, course TEXT, grade INTEGER)",[], function (tx, results) {
       tx.executeSql('INSERT INTO test(course,grade) VALUES ("Geography, World",90)');
       tx.executeSql('INSERT INTO test(course,grade) VALUES ("Health",92)');
       tx.executeSql('INSERT INTO test(course,grade) VALUES ("Literature, English",91)');
       tx.executeSql('INSERT INTO test(course,grade) VALUES ("Math 201",85)');
       tx.executeSql('INSERT INTO test(course,grade) VALUES ("Science 202",95)');

       tx.executeSql('SELECT * FROM test',[],function(result){


       },function(error) {
           alert("erorr..." + error);
       });
});