正在尝试创建webSQL数据库。已经进行了很长时间的故障排除,并尝试了许多不同的事情,但一无所获。将其简化为一个硬编码功能。 从Chrome中的开发人员工具来看,它似乎最初正在创建数据库,并立即将其删除。
有人知道我哪里出错了吗?对Javascript来说非常新,所以它可能很小。
谢谢。
<script>
function writeToDatabase(){
var my_array = new Array();
my_array[0] = "23 November 2013";
my_array[1] = "3:00 AM";
my_array[2] = "Go to the doctor for yearly checkup";
my_array[3] = "Doctor visit";
var db = openDatabase('events_db', '1.0', 'DB for storing event details', 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS EVENTS (id integer primary key autoincrement, date, time, description, title)');
tx.executeSql('INSERT INTO EVENTS (date, time, description, title) VALUES (?, ?, ?, ?)', my_array);
});
window.alert("done");
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM EVENTS', [], function (tx, results) {
var len = results.rows.length, i;
msg = "<p>Found rows: " + len + "</p>";
for (i = 0; i < len; i++){
window.alert(results.rows.item(i).description);
}
}, null);
});
}
</script>
我认为您需要执行创建 - 插入 - 选择操作作为每个操作的回调(在 db.transaction 中):
tx.executeSql('CREATE TABLE IF NOT EXISTS EVENTS (id integer primary key autoincrement, date, time, description, title)', [], function(tx) {
tx.executeSql('INSERT INTO EVENTS (date, time, description, title) VALUES (?, ?, ?, ?)', my_array, function(tx) {
tx.executeSql('SELECT * FROM EVENTS', [], function (tx, results) {
...
});
});
});
虽然这看起来很糟糕,但这就是WebSQL的工作方式。