简体   繁体   English

SQLite插件Cordova基本代码

[英]SQLite plugin Cordova basic code

I'm new to Cordova & Sqlite but I wrote some code and I can't figure out what is wrong with it? 我是Cordova&Sqlite的新手,但是我写了一些代码,但无法弄清楚这是怎么回事? Any suggestions? 有什么建议么? I always get the following output from the Javascript debugger: 我总是从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>

If you are testing a new plugin, library, … whatever, the best way is to read the docs, play a little bit with the examples and expand it step by step for your needs. 如果您要测试新的插件库,…等等,最好的方法是阅读文档,使用示例,然后逐步扩展以满足您的需求。

The SQLite plugin is event driven, that means, that you have to wait until the job is done. SQLite插件是事件驱动的,这意味着您必须等待作业完成。

You are doing it this way and this don't work: 你这样做是这样的,这工作:

var the_result = mySQL_Job();

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

The right way is: 正确的方法是:

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);
  });
}

This you have to do for every sql job, please see the docs at: https://github.com/litehelpers/Cordova-sqlite-storage 您必须为每个sql作业执行的操作,请参阅以下位置的文档: https : //github.com/litehelpers/Cordova-sqlite-storage

If you have a lot of queries then it is a good idea to use promises: How to compact SQL instructions in Cordova? 如果您有很多查询,那么最好使用promises: 如何在Cordova中压缩SQL指令?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM