【问题标题】:SQLite plugin Cordova basic codeSQLite 插件 Cordova 基本代码
【发布时间】:2016-02-05 13:29:22
【问题描述】:

我是 Cordova 和 Sqlite 的新手,但我写了一些代码,但我不知道它有什么问题?有什么建议? 我总是从 Javascript 调试器得到以下输出:

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>

【问题讨论】:

  • 你用过 SQLite 的插件吗?如果是,那么您也可以在没有任何插件的情况下使用 SQLite。查看链接:stackoverflow.com/questions/33879785/…
  • 请在此处阅读文档:github.com/litehelpers/Cordova-sqlite-storage 您的主要问题是,您的代码不是事件驱动的。您不能在事件驱动脚本中使用返回值。
  • @Dhruv 我使用 Joerg 描述的 SQLite 插件
  • @Joerg 事件驱动是什么意思?能举个小例子吗

标签: javascript sqlite cordova visual-studio-2015 cordova-plugins


【解决方案1】:

如果您正在测试一个新的插件、库……无论如何,最好的方法是阅读文档,稍微玩一下示例,然后根据您的需要逐步扩展它。

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

如果您有很多查询,那么最好使用 Promise:How to compact SQL instructions in Cordova?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 2015-02-28
    • 1970-01-01
    相关资源
    最近更新 更多