Android SQLite数据库blob数据类型

时间:2014-11-20 13:44:25

标签: android sqlite

我想在我的数据库中保存图像,但我不确定一件事

我在扩展SQLiteOpenHelper

的类上有这个方法
public boolean insertDemo(byte[] a, byte[] b, byte[] c, byte d) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("id", 1);
        cv.put("demo1", a);
        cv.put("demo2", b);
        cv.put("demo3", c);
        cv.put("demo4", d);
        db.insert("demo_tb", null, cv);
        return true;
}

我的问题是,数据类型应该是什么?目前我有

db.execSQL("create table demo_tb"+"(id integer primary key,demo1 text,demo2 text,demo3 text,demo4 text)");

onCreate方法中。

2 个答案:

答案 0 :(得分:2)

要在sqlite数据库中保存图像,您应该在表格中为该列使用BLOB数据类型。

答案 1 :(得分:0)

我使用BLOB类型,我看不出用好眼睛使用TEXT类型来保存字节数组

像这样:

protected static final String CREATE_TABLE_IMAGE = 
            "CREATE TABLE IMAGES"
            + "("
            + " IMAGE_ID"
            + " INTEGER PRIMARY KEY ,"
            + " IMAGE_BLOB"
            + " BLOB "
            +")";   

    public void CreateTable(String strCreate){
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL(strCreate);
    }

    public boolean saveBytes(byte[] bytes, int id){

        boolean ret = false;
        SQLiteDatabase db = getWritableDatabase();
        db.beginTransaction();

        try{

        String sql   =   "INSERT INTO IMAGES " 
                + " ( IMAGE_ID" 
                + ", IMAGE_BLOB" 
                + " ) VALUES(?,?)";

        SQLiteStatement insertStmt      =   db.compileStatement(sql);
        insertStmt.clearBindings();
        insertStmt.bindLong(1, id);
        insertStmt.bindBlob(2, bytes);
        insertStmt.executeInsert();

        db.setTransactionSuccessful();
        db.endTransaction();

        ret = true;
        }catch(Exception e){
            e.printStackTrace();
            ret = false;
        }

        return ret;
    }

    public byte[] getBytes( int id) throws Exception {

        byte[] ret = null;

        try {

            String selectQuery = "SELECT  I.IMAGE_BLOB " 
                    + "         FROM IMAGES I WHERE I.IMAGE_ID = ?";

            SQLiteDatabase db = this.getReadableDatabase();
            Cursor c = db.rawQuery(selectQuery,new String[]{String.valueOf(id)});


            if (!c.isClosed() && c.moveToFirst() && c.getCount() > 0) {

                if (c.getBlob(c.getColumnIndex("IMAGE_BLOB")) != null)
                {                   
                    ret = c.getBlob(c.getColumnIndex("IMAGE_BLOB"));

                }
                c.close();
                if (db != null && db.isOpen())
                    db.close();
            }
            System.gc();
        } catch (Exception e) {
            System.gc();
            throw e;

        }
    }