使用 Antair Cordova SQLitePlugin [帮助请求] 的离子预填充数据库 [英] Ionic Prepopulated Database with Antair Cordova SQLitePlugin [help request]

查看:40
本文介绍了使用 Antair Cordova SQLitePlugin [帮助请求] 的离子预填充数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

____ 简介

大家好,首先澄清三点:

  1. 我的英语不好,所以请原谅我的错误,
  2. 我是新手,请原谅我的不准确之处
  3. 我之前已经搜索并尝试过在互联网上找到的解决方案,但仍然无法解决嵌入预填充数据库的问题.

____ 目标

我想使用预填充数据库开发适用于 iOS 和 Android 的应用.

I want to develop an app for iOS and Android with a prepopulated database.

举例来说,数据库包含 15.000 条记录,每条记录由三个键值对(idfirstname>姓).

Just for example, the database consists of 15.000 records each one made of three key-value pair (id, firstname and lastname).

___ 我做了什么

步骤:

ionic start myapp blank
cd myapp
ionic platform add ios
ionic platform add android

然后我创建了一个用于测试目的的sqlite数据库,名为mydb.sqlite,由一张表people组成,其中包含两个idfirstnamelastname 记录.

Then I created an sqlite database for testing purpose, named mydb.sqlite, made of one table people containing two id, firstname, lastname records.

我决定使用以下插件:https://github.com/Antair/Cordova-SQLitePlugin那是因为它可以用cordova工具安装.

I decided to use the following plugin: https://github.com/Antair/Cordova-SQLitePlugin That's because it can be installed with cordova tool.

ionic plugin add https://github.com/Antair/Cordova-SQLitePlugin

(警告:我认为网站上的说明显示了不正确的参考 - "cordova plugin add https://github.com/brodysoft/Cordova-SQLitePlugin" - 指的是另一个插件.

(Alert: I think that the instructions on the website show an incorrect reference - "cordova plugin add https://github.com/brodysoft/Cordova-SQLitePlugin" - which refers to another plugin).

然后,按照插件网站上的说明,我将数据库复制到 myapp/www/db/,以便现在可以在 myapp/www/db/mydb 中找到它.sqlite

Then, following the instructions on the plugin website, I copied the database to myapp/www/db/ so that it can now be found at myapp/www/db/mydb.sqlite

我在默认 app.js 脚本之后修改了 index.html,包括 SQLite 插件:

I modified the index.html including the SQLite plugin just after the default app.js script:

<!-- your app's js -->
<script src="js/app.js"></script>
<script src="SQLitePlugin.js"></script>

我还在 index.html 文件中写了几行代码来显示一个按钮:

I also write some lines of code in index.html file to show a button:

<ion-content ng-controller="MyCtrl">
    <button class="button" ng-click="all()">All</button>
</ion-content>

最后我修改了./js/app.js:

// Ionic Starter App

var db = null;

angular.module('starter', ['ionic' /* What goes here? */ ])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // some predefined code has been omitted

    window.sqlitePlugin.importPrepopulatedDatabase({file: "mydb.sqlite", "importIfExists": true});
    db = window.sqlitePlugin.openDatabase({name: "mydb.sqlite"});

  }); // $ionicPlatform.ready
}) // .run

.controller('MyCtrl', function($scope){

    $scope.all = function(){
            var query = "SELECT * FROM people";
            // I don't know how to proceed

    }; // $scope.all

}); // .controller

___ 问题

我不知道如何在控制器部分继续查询所有记录(只是一个查询示例)并在 console.log 中显示结果.

I don't know how to proceed in the controller section to query all the records (just an example of query) and show the results in the console.log.

我认为下面的代码一定是通过某种方式完成的:

I think that the following code must be completed in some way:

angular.module('starter', ['ionic' /* What goes here? */ ]) 

并且必须完成控制器部分中的代码:

And also the code inside controller section must be completed:

       $scope.all = function(){
                var query = "SELECT * FROM people";
                // I don't know how to proceed

        }; // $scope.all

___ 最后的感谢

预先感谢您对我的帮助.

Thank you in advance for the help you will give to me.

推荐答案

所以这个家伙的代码对封装我的 DAL 有很大帮助.我强烈建议您几乎逐字使用他的代码.

So this guy's code has helped a lot to encapsulate my DAL. I highly recommend that you use he's code pretty much verbatim.

https://gist.github.com/jgoux/10738978

你会看到他有以下方法:

You'll see he has the following method:

self.query = function(query, bindings) {
    bindings = typeof bindings !== 'undefined' ? bindings : [];
    var deferred = $q.defer();

    self.db.transaction(function(transaction) {
        transaction.executeSql(query, bindings, function(transaction, result) {
            deferred.resolve(result);
        }, function(transaction, error) {
            deferred.reject(error);
        });
    });

    return deferred.promise;
};

让我们稍微分解一下.查询函数接受一个查询字符串(查询参数)和一个可能的绑定列表?在像SELECT * FROM A_TABLE WHERE ID = ?"这样的查询中.因为他的代码是一个服务,self 值指向服务本身以供未来所有调用.该函数将对数据库执行一个事务,但它返回一个只有在数据库返回后才会实现的承诺.

Let's break this down a bit. The query function takes a query string (the query param) and a list of possible bindings for ? in a query like "SELECT * FROM A_TABLE WHERE ID = ?". Because he's code is a service, the self value points to the service itself for all future invocations. The function will execute a transaction against the db, but it returns a promise that is only fulfilled once the db comes back.

他的服务提供了第二个辅助函数:fetchAll.

His service provides a second helper function: fetchAll.

self.fetchAll = function(result) {
    var output = [];

    for (var i = 0; i < result.rows.length; i++) {
        output.push(result.rows.item(i));
    }

    return output;
};

fetchAll 会将所有行读入一个数组.fetchAll 的结果参数是在查询函数的承诺履行中传递的结果变量.

fetchAll will read the rows in their entirety into an array. The result param for fetchAll is the result variable passed in the query function's promise fulfillment.

如果您将他的代码复制并粘贴到您的服务文件中,您现在就拥有了一个真正的数据库服务.您可以将该服务包装在 DAL 中.这是我的项目中的一个示例.

If you copy and paste his code into your service file, you now have a bonafide DB service. You can wrap that service up in a DAL. Here's an example from my project.

.service('LocationService', function ($q, DB, Util) {
    'use strict';
    var self = this;
    self.locations = [];
    self.loadLocked = false;
    self.pending = [];

    self.findLocations = function () {
        var d = $q.defer();
        if (self.locations.length > 0) {
            d.resolve(self.locations);
        }
        else if (self.locations.length === 0 && !self.loadLocked) {
            self.loadLocked = true;
            DB.query("SELECT * FROM locations WHERE kind = 'active'")
                   .then(function (resultSet) {
                       var locations = DB.fetchAll(resultSet);
                       self.locations.
                           push.apply(self.locations, locations);
                       self.loadLocked = false;
                       d.resolve(self.locations);
                       self.pending.forEach(function (d) {
                           d.resolve(self.locations);
                       });
                   }, Util.handleError);
            } else {
                self.pending.push(d);
            }

            return d.promise;
        };
})

这个例子有点嘈杂,因为它有一些线程"代码来确保相同的承诺是否被触发两次,它只对数据库运行一次.一般点是表明 DB.query 返回一个承诺.查询方法后面的then"使用DB服务来获取所有数据并将其添加到我的本地内存空间中.所有这些都由返回变量 d.promise 的 self.findLocations 协调.

This example is a bit noisy since it has some "threading" code to make sure if the same promise is fired twice it only runs against the DB once. The general poin is to show that the DB.query returns a promise. The "then" following the query method uses the DB service to fetchAll the data and add it into my local memory space. All of this is coordinated by the self.findLocations returning the variable d.promise.

您的代表也类似.控制器可以将您的 DAL 服务(例如我的 LocationService)通过 AngularJS 注入其中.如果您使用的是 AngularJS UI,您可以让它解析数据并将其传递到列表中.

Yours would behalf similarly. The controller could have your DAL service, like my LocationService, injected into it by AngularJS. If you're using the AngularJS UI, you can have it resolve the data and pass it into the list.

最后,我对这家伙的代码唯一的问题是数据库应该来自这段代码.

Finally, the only issue I have with the guy's code is that the db should come from this code.

var dbMaker = ($window.sqlitePlugin || $window);

这样做的原因是该插件在 Apache Ripple 中不起作用.由于该插件很好地反映了浏览器的 Web SQL 界面,这个简单的小改动将使 Ripple 能够运行您的 Ionic 应用程序,同时仍然允许您在真实设备上运行您的 SQLite.

The reason for this is that the plugin does not work within Apache Ripple. Since the plugin does a fine job mirroring the Web SQL interface of the browser, this simple little change will enable Ripple to run your Ionic Apps while still allowing you to work your SQLite in a real device.

我希望这会有所帮助.

这篇关于使用 Antair Cordova SQLitePlugin [帮助请求] 的离子预填充数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆