SQLITE with Android (best methodology for setting up a database)

前端 未结 1 835
臣服心动
臣服心动 2020-12-11 10:32

I have seen a few different ways that you can utilize SQLite as the database for your app. They are as follows:

  • Database is created and data is imported via a
相关标签:
1条回答
  • 2020-12-11 11:00

    One option which I did:

    • Store each of the schema and data population files as scripts in resources
    • Created a wrapper class that runs those scripts from resources
    • One of the resource files is a well known (by name) manifest, it has a list of the scripts to run in which order.
    • I have a poperties table in the database which stores what's the last script that ran.

    That means:

    • On creation (first run) - it runs all scripts in succession
    • When app is updates - it runs all scripts that haven't run yet. The update carries more scripts in resources.

    The scripts update schema and modify/munge existing customer data - of course without data loss.

    BTW, I did this on iOS with the intent of sharing those sqlite scripts between android, winphone and other platforms. You just need the wrapper class on each platform that runs the sequences.

    It also means I can run the scripts in order from the cmdline to create a db if needed ...

    EDIT:

    For example, in my sample app, Update1.sql is a file added as a resource. It has two sql batches in it. My wrapper opens the manifest file, get's the list of scripts to run, queries the database to see the last script ran, then creates an array of scripts to run. When it runs Update1.sql which is in the list, my wrapper class executes all the statements in that file thats embedded as a resource. For example, here's my Update1.sql

    alter table messages add column user text;
    
    create table log
    (
        id integer primary key autoincrement, 
        information text    
    );
    

    Now, let's say the new table created needs some data in it. (in my case a log table doesn't). That scripts could contain a series of insert into statements right after the create table.

    Executing multiple batches in a script requires the use of the tail argument in prepare. I have C/objective-c code if you would like to see it but I haven't written the android wrapper yet ...

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