简体   繁体   中英

import a table into an existing SQLite database

In my app, at first launch, I download a pre-populated database from the web. (rather quick)

And every x times, I need to update one table in the database. I don't need the old entries so I can delete them.

Here is what I do: I delete all the content of my table. And then I get a csv file with my data from the web and I used Statement (to optimize) to do lots of inserts... But, it takes several minutes (thousands of rows).

So, I was wondering, since I don't need the old entries, how about dropping the table and importing the new one from the web? This way, I would avoid the inserts and it should be faster.

Is that possible?

EDIT:

Here is my code, please correct me if it can be optimized:

int size = 5;
SQLiteStatement statement = myDB.compileStatement("insert into " + TABLE + " values(?, ?, ?, ?, ?, ?)");
        String data[];
        String line = null;
        int size = 5;
//...
//some code    
//...
myDB.beginTransaction();


    while((line = bufferedReader.readLine()) != null) {
        data = line.replaceAll("'", "''").split(",", -1);

        statement.clearBindings();
        for(int i = 0; i < size; i++) {
            statement.bindString(i + 1, data[i]);
        }
        statement.bindString(size + 1, deadline);
        statement.executeInsert();
    }

    myDB.setTransactionSuccessful();    
    myDB.endTransaction();

And just to clarify, I don't want to DELETE my database since I want to KEEP all the other tables in my database, that's why I'm asking if it is possible to import (and replace) only one table into a database with other tables.

Yes, it is possible but you have to use it with caution.

You can download the file and paste it in the databases folder after removing your old database file. Use Android context to get the file path for library instead of hardcoding it.

You have to be cautious as the sqlite versions that you use to create the database and what the device is using might be different.

Another approach that I would recommend if you haven't already done this is to use your own transaction. Start transaction before you start your inserts and close the transaction after you have inserted your rows. One reason why it might be slow is because Android does inserts by starting a transaction for each insert but will not do it if you do it yourself.

beginTransaction and endTransaction are the methods that you are looking for on the SQLiteDatabase if you follow second approach.

EDIT:

If you do not want to delete the entire database, I would recommend the second approach of transactions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM