作者: 赵晓伟 | 来源:互联网 | 2023-05-20 19:18
您好我正在使用离子框架和cordova创建一个应用程序,并希望使用sqlite数据库来存储数据.
那么如何才能将现有的sqlite数据库用于此目的呢?我在哪里保存数据库,以便cordova可以找到它并在我编译平台时使用它?
编辑:
如果我尝试以推荐的方式打开数据库,则会出现以下错误:
[Error] TypeError: undefined is not an object (evaluating 'n.sqlitePlugin.openDatabase')
openDB (ng-cordova.min.js, line 9)
(anonyme Funktion) (app.js, line 19)
(anonyme Funktion) (ionic.bundle.js, line 44243)
onPlatformReady (ionic.bundle.js, line 2396)
onWindowLoad (ionic.bundle.js, line 2375)
这是我的index.html的head部分:
我的app.js看起来像这样:
//Database variable
var db = null;
angular.module('starter', ['ionic', 'starter.controllers', 'ngCordova'])
.run(function($ionicPlatform, $cordovaSQLite) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
db = $cordovaSQLite.openDB({ name: "db.spareParts" });
var query = "SELECT cars.name FROM cars";
$cordovaSQLite.execute(db, query).then(function(res) {
if(res.rows.length > 0) {
console.log("SELECTED -> " + res.rows.item(0).name);
} else {
console.log("No results found");
}
}, function (err) {
console.error(err);
});
});
})
数据库db.spareParts存储在根www目录中,是一个sqlite3数据库.
1> Awad Haj..:
经过很长时间的痛苦我修复了这个问题:)
预填充数据库必须位于应用程序的"dataDirectory"中
首先你需要检查那个目录中是否存在db文件,如果没有,你必须从应用程序目录中复制它(即/ www文件夹)
检查这段代码
$ionicPlatform.ready(function() {
src = cordova.file.dataDirectory + 'data.sqlite';
window.resolveLocalFileSystemURL(src, function () {
db = sqlitePlugin.openDatabase('data.sqlite');
}, function () {
$scope.copyDb('data.sqlite');
});
$scope.copyDb = function (dbName) {
var sourceFileName = cordova.file.applicationDirectory + 'www/' + dbName;
var targetDirName = cordova.file.dataDirectory;
return Promise.all([
new Promise(function (resolve, reject) {
resolveLocalFileSystemURL(sourceFileName, resolve, reject);
}),
new Promise(function (resolve, reject) {
resolveLocalFileSystemURL(targetDirName, resolve, reject);
})
]).then(function (files) {
var sourceFile = files[0];
var targetDir = files[1];
return new Promise(function (resolve, reject) {
targetDir.getFile(dbName, {}, resolve, reject);
}).then(function () {
console.log("file already copied");
}).catch(function () {
console.log("file doesn't exist, copying it");
return new Promise(function (resolve, reject) {
sourceFile.copyTo(targetDir, dbName, resolve, reject);
}).then(function () {
console.log("database file copied");
db = sqlitePlugin.openDatabase('data.sqlite');
});
});
});
};
检查此链接
预填充的db演示