Sqlite:检查数据库是否存在 [英] Sqlite: check if database exist
问题描述
我正在使用phonegap开发一个移动应用程序,将一些数据存储到本地数据库(sqlite DB)。
我需要知道数据库是否存在,并确定哪个进程需要执行。
I am developing a mobile application using phonegap that store some data into the local database (sqlite DB). I need to know if the database exist or not, and that to determine which process need to execute.
var database = window.openDatabase("my_db", "1.0", "sample DB", 30000);
if (check_db_exist()) {
process_1();
}
else
{
process_2();
}
推荐答案
,我需要检查应用程序是否已经创建了数据库(旧数据库),如果是这样,则将所有数据导出到新数据库(新的和改进的数据库),然后删除此数据库。
I needed to do something similar, I needed to check if the application had a db already created (legacy DB) and if so export all the data to the new db (new and improved DB) and then delete this DB.
背景信息:我从简单的键值表移动到具有级联等的复杂的关系数据库。
Background Info: I was moving from simple keyvalue tables to complex relational DB with cascades etc.
function onDeviceReady() {
// CHECK IF LEGACY DATABASE EXISTS. IF DOES EXPORT EXISTING DATA TO NEW DB THEN DELETE LEGACY
window.resolveLocalFileSystemURL(cordova.file.applicationStorageDirectory + "/databases/<DatabaseName>.db", exportToNewDB, setupDB);
}
注意:如果文件存在(成功),那么我们需要执行导出代码在这里,然后删除文件,所以这个方法将总是失败。如果文件不存在 - 用户已经导出到新的数据库,或者他们是我们的新用户,从来没有遗留数据库。
Note: If file exists (success), then we need to do our export code in here, then delete file so this method will always fail. If file doesn't exist - user has already exported to new DB or they our new user and never had legacy DB.
// Fail Method
function setupDB() {
newDB = window.sqlitePlugin.openDatabase({ name: "<NewImprovedDBName>.db" });
newDB.transaction(sql.initDB, sql.errorCallback, sql.successCallBack);
}
// Success Method
function exportToNewDB() {
db = window.sqlitePlugin.openDatabase({ name: "<LegacyDBName>.db" });
db.transaction(function (tx) {
setupDB();
// Insert Export code Here
// Delete DB
window.sqlitePlugin.deleteDatabase("<LegacyDBName>.db", sqlSuccess, sqlFail);
}, sqlFail);
}
回答您的问题:
window.resolveLocalFileSystemURL(cordova.file.applicationStorageDirectory + "/databases/my_db.db", process_1, process_2);
这篇关于Sqlite:检查数据库是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!