2017-07-18 56 views

回答

0

我找到了另一種方式,使用Cordova-sqlite-storage 只需使用不同的數據庫對象的瀏覽器和設備。

我的代碼:

var runiOS = false; 
var DB; 

// Check browser or device 

var onDeviceReady = new Promise(function(resolve, reject) {  
    if (document.URL.match(/^https?:/i)) { 
     console.log("Running in a browser..."); 
     resolve(); 
    } else { 
     console.log("Running in an app..."); 
     runiOS = true; 
     document.addEventListener("deviceready", resolve, false); 
    } 
}); 

// Run application 
onDeviceReady.then(function() { 
    // Init WebSQL on browser or SQLite on device 
    if (runiOS) { 
     DB = window.sqlitePlugin.openDatabase({ name: 'my.db', location: 'default' }, function (db) {}, function (error) { console.log('Open database ERROR: ' + JSON.stringify(error)); });   
     console.log('DB: SQLite'); 
    } 
    else { 
     DB = window.openDatabase('my', "0.1", "My list", 200000);  
     console.log('DB: WebSQL'); 
    } 

    // ... 

    db.transaction(function(tx) { 
     tx.executeSql('CREATE TABLE IF NOT EXISTS DemoTable (name, score)'); 
     tx.executeSql('INSERT INTO DemoTable VALUES (?,?)', ['Alice', 101]); 
     tx.executeSql('INSERT INTO DemoTable VALUES (?,?)', ['Betty', 202]); 
    }, function(error) { 
     console.log('Transaction ERROR: ' + error.message); 
    }, function() { 
     console.log('Populated database OK'); 
    }); 


    db.transaction(function(tx) { 
     tx.executeSql('SELECT count(*) AS mycount FROM DemoTable', [], function(tx, rs) { 
      console.log('Record count (expected to be 2): ' + rs.rows.item(0).mycount); 
     }, function(tx, error) { 
      console.log('SELECT error: ' + error.message); 
     }); 
    }); 
}); 
+0

確信此代碼沒有任何錯誤運行? – NaveenDA

+0

這只是初始化的例子。當然這個代碼不能運行。我將編輯答案。 –

相關問題