我想将SQLite数据添加到离子中的移动应用程序中,我已经按照以下站点中的教程逐步进行操作 https://blog.nraboy.com/2014/11/use-sqlite-instead-local-storage-ionic-framework/但它仍然无法在物理设备上工作,任何建议。在索引中.html我输入以下代码 `
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ionic/js/angular-ui/angular-ui-router.js"></script>
<script src="lib/ionic/js/angular/angular-resource.js"></script>
<!-- Needed for Cordova/PhoneGap (will be a 404 during development) -->
<script src="js/app.js"></script>
<script src="js/ng-cordova.min.js"></script>
<script src="cordova.js"></script>`
在我的应用程序中.js我首先编写了以下代码
var db=null;
var myApp=angular.module('myApp',['ionic','ngCordova'])
.run(function($ionicPlatform, $cordovaSQLite) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
db = $cordovaSQLite.openDB("test.db");
$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS people (id integer primary key, firstname text, lastname text)");
console.log("hello");
})
}(
所以我创建了一个名为 people 的表,在我的登录控制器中,我将在 people 表中插入一行
controller('loginController',function($scope,$cordovaSQLite){
var query = "INSERT INTO people (id,firstname, lastname) VALUES (?,?,?)";
$cordovaSQLite.execute(db, query, [1,"khaled", "omar"]).then(function(res) {
$scope.name=res.insertId;
}, function (err) {
$scope.name="error";
});
在登录名中.html我写了{{name}},但是当我在浏览器上运行它时,出现以下错误 无法读取未定义的属性"openDatabase",我在物理设备上运行它,但仍然不起作用
运行良好,似乎错误来自控制器中的问题。
代码对我有用。
我不知道为什么,但是您必须将数据库创建代码放在onReady
方法中,然后if
语句,如下所示:
.run(function($ionicPlatform,$cordovaSQLite) {
$ionicPlatform.ready(function() {
db = $cordovaSQLite.openDB({name:"my.db", location:1});
$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS testTable(id integer primary key, col1 text,col2 tex)");
if(window.cordova && window.cordova.plugins.Keyboard) {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
// Don't remove this line unless you know what you are doing. It stops the viewport
// from snapping when text inputs are focused. Ionic handles this internally for
// a much nicer keyboard experience.
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
您应该使用以下代码。
db = $cordovaSQLite.openDB({name: "dbname.db", location: 1});
它会起作用。
$ionicPlatform.ready(( 必须先触发,然后才能使用 cordova。
这实际上奏效了,谢谢 musakkhir 和 anuj
db = $cordovaSQLite.openDB({name: "dbname.db", location: 1});
location:1
很重要。