如何使用window.openDatabase访问phonegap中的旧数据库?

时间:2012-06-19 19:39:12

标签: cordova

我在PhoneGap开发页面中阅读了存储教程。 在该示例中,它使用了window.openDatabase两次。但文档说openDatabase返回一个新的db对象,我想这个例子的目标是生成一个新的DB,然后访问它以获取数据。但是为什么它会两次创建一个新的db对象?

<!DOCTYPE html>
<html>
  <head>
    <title>Storage Example</title>

    <script type="text/javascript" charset="utf-8" src="cordova-1.8.1.js"></script>
    <script type="text/javascript" charset="utf-8">

    // Wait for Cordova to load
    //
    document.addEventListener("deviceready", onDeviceReady, false);

    // Populate the database 
    //
    function populateDB(tx) {
        tx.executeSql('DROP TABLE IF EXISTS DEMO');
        tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
        tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")');
        tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
    }

    // Query the database
    //
    function queryDB(tx) {
        tx.executeSql('SELECT * FROM DEMO', [], querySuccess, errorCB);
    }

    // Query the success callback
    //
    function querySuccess(tx, results) {
  console.log("Returned rows = " + results.rows.length);
  // this will be true since it was a select statement and so rowsAffected was 0
  if (!results.rowsAffected) {
    console.log('No rows affected!');
    return false;
  }
  // for an insert statement, this property will return the ID of the last inserted row
  console.log("Last inserted row ID = " + results.insertId);
    }

    // Transaction error callback
    //
    function errorCB(err) {
        console.log("Error processing SQL: "+err.code);
    }

    // Transaction success callback
    //
    function successCB() {
        var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000); //Why create a new DB again??
        db.transaction(queryDB, errorCB);
    }

    // Cordova is ready
    //
    function onDeviceReady() {
        var db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
        db.transaction(populateDB, errorCB, successCB);     //upon the success of create a database, jump to successCB
    }

    </script>
  </head>
  <body>
    <h1>Example</h1>
    <p>Database</p>
  </body>
</html>

2 个答案:

答案 0 :(得分:3)

对window.openDatabase的调用将返回一个新的db对象,但是如果要求相同的数据库名称,在本例中为“Database”,则每个db对象将引用相同的物理数据库。

答案 1 :(得分:3)

另一个好问题是:为什么要打开数据库两次?只需执行一次并全局存储返回的对象。

var db;
document.addEventListener("deviceready", function() {
    db = window.openDatabase("Database", "1.0", "Cordova Demo", 200000);
}, false);