我正在尝试对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>
代码有什么问题吗?
答案 0 :(得分:1)
代码中没有成功和错误方法。 尝试这种方式,以便您可以知道错误的位置:
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!");
}
答案 1 :(得分:1)
试试这个:
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);
});
});
}