Efficient batch SQL query execution on Android, for upgrade database

≯℡__Kan透↙ 提交于 2019-12-18 12:34:40

问题


As we Android developers know, the SQLiteDatabase execSQL method can execute only one statement.

The doc says:

Execute a single SQL statement that is not a query. For example, CREATE TABLE, DELETE, INSERT, etc. Multiple statements separated by ;s are not supported.

I have to load in a batch of records, 1000 and counting.
How do I insert these efficiently?
And what's the easiest way to deliver these SQLs with your apk?

I mention, there is already a system database and I will run this on the onUpdate event.

I have this code so far:

List<String[]> li = new ArrayList<String[]>();
        li.add(new String[] {
                "-1", "Stop", "0"
        });
        li.add(new String[] {
                "0", "Start", "0"
        });
    /* the rest of the assign */
try {
        for (String[] elem : li) {
            getDb().execSQL(
                    "INSERT INTO " + TABLENAME + " (" + _ID + "," + NAME + "," + PARSE_ORDER
                            + ") VALUES (?,?,?)", elem);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

回答1:


How do I insert these efficiently?

Use transaction:

    db.beginTransaction();
    try {
        for(;;) {
            db.execSQL(...);
            }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }



回答2:


I think what you have is the only way to load those 1000 records, now, as far as deploying that DB with your apk file, check out this post:

http://www.helloandroid.com/tutorials/how-have-default-database



来源:https://stackoverflow.com/questions/2876236/efficient-batch-sql-query-execution-on-android-for-upgrade-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!