Retrieve large blob from Android sqlite database

后端 未结 2 771
心在旅途
心在旅途 2020-11-29 05:36

I stored chunks of binary data (protobufs) in the sqlite database of an Android app without realizing that Android\'s Cursor can only hold a maximum of 1MB of d

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 05:44

    CL. answer will only with blobs<5MB. If you tried to use it with blobs bigger than 5 megabytes you will still get the exception. To fetch large blobs you need to use a library called sqlite4java that uses native calls to the database without using cursors. Here is an example of using this library to fetch a large blob:

    SQLiteConnection sqLiteConnection=null;
    SQLiteStatement sqLiteStatement=null;
    try
    {
        File databaseFile = context.getDatabasePath("database.db");
        sqLiteConnection=new SQLiteConnection(databaseFile);
        sqLiteConnection.open();
        sqLiteStatement=sqLiteConnection.prepare("SELECT blob FROM table WHERE id=?");
        sqLiteStatement.bind(1, id);
        sqLiteStatement.step();
        byte[] blob=sqLiteStatement.columnBlob(0);
    }
    finally
    {
        if(sqLiteStatement!=null)
            sqLiteStatement.dispose();
        if(sqLiteConnection!=null)
            sqLiteConnection.dispose();
    }
    

提交回复
热议问题