Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlite: check if database exist

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();
}
like image 845
Moussawi7 Avatar asked Oct 21 '22 13:10

Moussawi7


2 Answers

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);
}

Answer to your Question:

window.resolveLocalFileSystemURL(cordova.file.applicationStorageDirectory + "/databases/my_db.db", process_1, process_2);
like image 152
tyler_mitchell Avatar answered Oct 23 '22 06:10

tyler_mitchell


The best way for determining if the DB exists or not is to check if the file that represents it exists. This is a simple IO operation, like the following example:

string path = Path.Combine(ApplicationData.Current.LocalFolder.Path, databaseName);

if (File.Exists(path)) { //your code here }

like image 39
Samuelens Avatar answered Oct 23 '22 05:10

Samuelens