Skip to main content
 首页 » 编程设计

angularjs之从 ionic 中预先填充的数据库文件中读取数据

2025年05月04日99tuyile006

我是 ionic 框架的新手。我正在从 ionic 中填充的数据库文件中读取数据。数据库文件是 json 格式。在 json 文件中,我的数据库名称、表名称和数据可用。如何在 ionic 中使用 angularjs 从此数据库文件中读取数据

我遵循了本教程:https://www.thepolyglotdeveloper.com/2015/01/deploy-ionic-framework-app-pre-filled-sqlite-db/

var db; 
angular.module('starter', ['ionic', 'starter.controllers', 'ngCordova']) 
    .run(function ($ionicPlatform, $cordovaSQLite) {`enter code here` 
        $ionicPlatform.ready(function () { 
            if (window.cordova && window.cordova.plugins.Keyboard) {       
                cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); 
                cordova.plugins.Keyboard.disableScroll(true); 
            } 
            if (window.StatusBar) { 
                StatusBar.styleDefault(); 
            } 
 
            window.plugins.sqlDB.copy("gr.json", function() { 
                db = $cordovaSQLite.openDB("grocery.db"); 
              }, function(error) { 
                console.error("There was an error copying the database: " + error); 
                db = $cordovaSQLite.openDB("grocery.db"); 
            }); 
 
        }); 
    }) 

这是我的controller.js

angular.module('starter.controllers', []) 
    .controller("ExampleController", function ($scope, $cordovaSQLite) { 
        $scope.selectAll = function(){ 
            var query = "SELECT * FROM grocery1"; 
            $cordovaSQLite.execute(db, query, []).then(function(res) { 
                if(res.rows.length > 0) { 
                    alert("in query"); 
                    for(var i = 0; i < res.rows.length; i++) { 
                    } 
                } else { 
                    alert("no response"); 
                } 
            }, function (err) { 
                alert("Error"); 
        }); 
    }; 
}); 

这是我的数据库文件 gs.json,我使用 sqlite studio 生成了这个文件。我添加了一些行。我想阅读这些添加的行。

{ 
    "type": "database", 
    "name": "grocery", 
    "objects": [{ 
        "type": "table", 
        "database": null, 
        "name": "grocery1", 
        "withoutRowId": true, 
        "ddl": "CREATE TABLE grocery1 (name CHAR (20))", 
        "columns": [{ 
            "name": "name", 
            "type": "CHAR" 
        }], 
        "rows": [ 
            [ 
                "sdd" 
            ], 
            [ 
                "adddd" 
            ], 
            [ 
                "add" 
            ], 
            [ 
                "asd" 
            ], 
            [ 
                "aaa" 
            ] 
        ] 
    }] 
} 

请帮助我如何从这个文件中读取数据。我收到错误警报。光标未进入执行函数内部。有没有其他方法可以从 ionic 数据库文件中读取数据?

请您参考如下方法:

在我的一个项目中,我使用了这个插件,它在产品应用程序中也能顺利运行。可以试试吗? https://github.com/an-rahulpandey/cordova-plugin-dbcopy/blob/master/plugin.xml