0

试图创建一个 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>
4

1 回答 1

1

我认为您需要执行 CREATE - INSERT - SELECT 操作作为每个操作的回调(在 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 的工作方式。

于 2013-11-04T19:29:48.220 回答