Websql 不适用于 phonegap 构建

Websql not working on phonegap build

我正在 phonegap 上尝试基本 sql 操作,但它显示空白页。 sql 操作在 safari 上正常工作。

代码如下:

<!DOCTYPE HTML>
<html>
<head>
<script src="cordova.js"></script>
<script type="text/javascript">
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
var msg;
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, log)');
tx.executeSql('INSERT INTO DEMO (id, log) VALUES (1, "foobar")');
tx.executeSql('INSERT INTO DEMO (id, log) VALUES (2, "logmsg")');
msg = '<p>Log message created and row inserted.</p>';
document.querySelector('#status').innerHTML =  msg;
});

db.transaction(function (tx) {
tx.executeSql('SELECT * FROM DEMO', [], function (tx, results) {
var len = results.rows.length, i;
msg = "<p>Found rows: " + len + "</p>";
document.querySelector('#status').innerHTML +=  msg;
for (i = 0; i < len; i++){
 msg = "<p><b>" + results.rows.item(i).log +"</b></p>";
 document.querySelector('#status').innerHTML +=  msg;
}
}, null);
});
</script>
</head>
<body>
<div id="status" name="status">Status Message</div>
</body>
</html>   

代码有问题吗?

您的代码中没有成功和错误方法。 试试这个方法,这样你就知道哪里出错了:

db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
db.transaction(createDB, errorCB, successCB);

function createDB(tx) {
      tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, log)');
      tx.executeSql('INSERT INTO DEMO (id, log) VALUES (1, "foobar")');
      tx.executeSql('INSERT INTO DEMO (id, log) VALUES (2, "logmsg")');

      console.log("Table created");
}

function errorCB(tx, err) {
        console.log("Error processing SQL: "+err);
    }

function successCB() {
        console.log("DB success!");

}

试试这个:

var db = openDatabase('CBDB', '1.0','mySpecialDatabaseThatWontWork',10*1024*1024);

db.transaction(function (tx){
tx.executeSql('DROP TABLE IF EXISTS cb');
alert("dropped table");
createDB();
queryDB();
},
function (tx, error) {
// error
alert('0.Something went wrong: '+ error.message);
});

function createDB(){
db.transaction(function (tx) {       
    tx.executeSql('CREATE TABLE IF NOT EXISTS cb (id unique, text)');
    tx.executeSql('INSERT INTO cb (id, text) VALUES (1, "myTest")');
    tx.executeSql('INSERT INTO cb (id, text) VALUES (2, "another")');
    tx.executeSql('INSERT INTO cb (id, text) VALUES (3, "andYetAnother")');
    tx.executeSql('INSERT INTO cb (id, text) VALUES (4, "ohAndAgain")');
    alert("DB success");  
    },
    function (tx, error) {
        // error
        alert('1.Something went wrong: '+ error.message);
    });
} 

function queryDB(){
db.transaction(function (tx) {
    tx.executeSql('SELECT * FROM cb',[], function (tx, results) {
        var rows = results.rows;
        alert(rows.length);
        for (var index = 0; index < rows.length; index++) {
            var x = rows.item(index);
            alert(x.text);
        } 
    },
    function (tx, error) {
    // error
    alert('2.Something went wrong: '+ error.message);
    });
});
}