0

我是新来的科尔多瓦& Sqlite,但我写了一些代码,我无法弄清楚它有什么问题吗?有什么建议么? 我总是从JavaScript调试器的输出如下:SQLite插件科尔多瓦基本代码

Click to see error messages

<script type="text/javascript"> 
    // Wait for Cordova to load 
    document.addEventListener('deviceready', onDeviceReady, false); 
    var output = document.getElementById('outputField'); 

    // Cordova is ready 
    function onDeviceReady() { 
     window.sqlitePlugin.openDatabase({ name: 'test.db', location: 2 }, function (db) { 
      output.innerHTML += '</br> - Database created/opened'; 

      db.transaction(function (tx) { 
       tx.executeSql(tx, "CREATE TABLE localStorage2 IF NOT EXISTS (key UNIQUE, value)"); 
      }); 


      output.innerHTML += '</br> - Table localStorage2 Created'; 

      storeValue(db, 'localStorage2', 'testKey', 'testValue'); 
      output.innerHTML += '</br> - Insert dummy value'; 

      output.innerHTML += '</br> ' + readValue(db, 'localStorage2', 'testKey'); 
     }); 
    } 


    function storeValue(db, table, key, value) { 
     db.transaction(function (tx) { 
      tx.executeSql(tx, 'INSERT INTO ' + table + ' (key,value) VALUES ("' + key + '","' + value + '")'); 
     }); 

    } 

    function readValue(db, table, key) { 
     db.transaction(function (tx) { 
      return db.executeSql(tx, 'SELECT * FROM ' + table + ' WHERE key="' + key + '"'); 
     }); 
    } 
</script> 
+0

你用过SQLite的插件吗?如果是的话,那么你也可以使用SQLite没有任何插件。检查链接:http://stackoverflow.com/questions/33879785/cordova-sqlite-plugin-not-functioning-with-android-studio/33894275#33894275 – Dhruv

+0

请阅读文档在这里:https://github.com/litehelpers/Cordova-sqlite-storage你的主要问题是,你的代码不是事件驱动的。您不能在事件驱动脚本中使用返回值。 – Joerg

+0

@Dhruv我使用Joerg描述的SQLite插件 – MichaelW

回答

0

如果你正在测试一个新的插件,图书馆,...什么的,最好的办法是阅读的文档,玩一点点随着例子,并一步一步扩大您的需求。

SQLite插件是事件驱动的,也就是说,你必须等到作业完成。

你做这种方式,这工作:

var the_result = mySQL_Job(); 

function mySQL_Job(){ 
    db.readTransaction(function(tx) { 
     return db.executeSql(…); 
    }); 
} 

正确的做法是:

mySQL_Job(); 

function mySQL_Job(some_values){ 
    tx.executeSql("SELECT * FROM myTable", [], function(tx, res) { 

     //Here goes your result handling, like inserting values in your html 

}, function(error) { 
    console.log('SQLite error: ' + error.message); 
    }); 
} 

这你必须为每一个SQL工作要做,请参阅该文档在:https://github.com/litehelpers/Cordova-sqlite-storage

如果您有很多查询,那么使用承诺是一个好主意:How to compact SQL instructions in Cordova?