本文介绍了Android SQLite 数据库 blob 数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将图像保存在我的数据库中,但我不确定一件事
I want to save Images in my database but I am not sure of one thing
我在扩展 SQLiteOpenHelper 的类上有这个方法
I have this method on the class that extends 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; }我的问题是,数据类型应该是什么?目前我有
My question is,what should the datatype be? currently I have
db.execSQL("create table demo_tb"+"(id integer primary key,demo1 text,demo2 text,demo3 text,demo4 text)");在 onCreate 方法中.
推荐答案我用的是BLOB类型,我没看好用TEXT类型来保存字节数组
I use the BLOB type, I do not see with good eyes use TEXT type to save an array of bytes
像这样:
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 = dbpileStatement(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; } }更多推荐
Android SQLite 数据库 blob 数据类型
发布评论