Sqlite: check if database exist

后端 未结 3 1019
野的像风
野的像风 2021-01-19 02:47

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 determ

相关标签:
3条回答
  • 2021-01-19 03:00

    I don't think that you can check for the existence of the DB directly. I've researched and haven't found a way to do it using a simple function call. However, this seems to be a popular request, and here's a workaround:

    var db = window.openDatabase("my.db", "1", "Demo", -1);
    
    
    db.transaction(function (tx) {
    
    /*I don't think that there is a way to check if a database exists.
        As I think that the openDatabase call above will just create
        a missing DB. Here is a second-best way to do it - there 
        is a way to check to see if a table exists.  Just pick a table that 
        your DB should have and query it.  If you get an ERROR, then you 
        can assume your DB is missing and you will need to create it. */
    
    console.log("Trying to get the test data");
    tx.executeSql("select * from test_table", [], function (tx, res) {
    
        var len = res.rows.length, i;
        for (i = 0; i < len; i++) {
            console.log(res.rows.item(i).data);
        }
    }, function (err) {
        console.log("Error selecting: " + err);
    
        //NOW we need to create the DB and populate it
        tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text)');
    
        tx.executeSql('INSERT INTO test_table (data) VALUES("test data one")');
        tx.executeSql('INSERT INTO test_table (data) VALUES("test data two")');
    
        //now test select
        tx.executeSql("select * from test_table", [], function (tx, res) {
    
            var len = res.rows.length, i;
            for (i = 0; i < len; i++) {
                console.log(res.rows.item(i).data);
            }
        });
    
    
        //now clean up so we can test this again
        tx.executeSql('DROP TABLE IF EXISTS test_table', [], function (tx, res) {
            console.log("dropped table");
        }, function (err) {
            console.log("Error dropping table: " + err);
        });
    
    });
    });
    

    As you can see, the error function during the first query will create and populate the DB. It's using exception handling for program logic flow, but it works!

    0 讨论(0)
  • 2021-01-19 03:03

    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);
    
    0 讨论(0)
  • 2021-01-19 03:04

    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 }

    0 讨论(0)
提交回复
热议问题