Android SQLite 数据库 存取 BLOB 二进制

时间:2021-07-07 05:34:29


作者: 东方闲仁

   Android开发时用到二进制数据(也可以理解为BYTE数组)的SQLite存取,可能会有人对存取如mp3、图片类文件困惑,其实p3、图片类文件读到内存就可理解为BYTE数组,只要在 下面的基础上增加将文件读到BYTE数组就可以了,其他操作是相同的(在网上搜了一段代码放下面了)。

  写此文的目的是方便自己今后查询,当然碰巧方便了其他人就当我奉献了:)


package com.Jung.DH;

 

import java.io.ByteArrayOutputStream;

import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.database.SQLException;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

import android.database.sqlite.SQLiteDatabase.CursorFactory;

import android.util.Log;

 

// 数据操作类

public class testSeedDB {

    private Context mContext = null; 

    private testDBHelper mDBHelper = null; 

    private SQLiteDatabase mTestDatabase = null; 

 

    private static final String DATABASE_NAME = "DHSeedData.db";  

    private static final int DATABASE_VERSION = 1;  

    private static final String TABLE_SEED = "TBseed";  

    private static final String TABLE_INFO = "TBinfo" 

 

    // 构造函数,一个引用类的Context作为参数

    public testSeedDB(Context context){ 

        mContext = context; 

    }

    // 打开数据库  

    public void open(){

        mDBHelper = new testDBHelper(mContext,DATABASE_NAME, null, DATABASE_VERSION); 

        mTestDatabase = mDBHelper.getWritableDatabase(); 

        Log.i("testSeedDB", "open");

    } 

    // Close the database

    public void close(){ 

         mDBHelper.close(); 

    }  

   

    public void CreateSeedTable() {  

    // 创建数据表是先删除以前的,以免出错

       String sql = "drop table "+ TABLE_SEED;

    try {

        mTestDatabase.execSQL(sql);

    } catch (SQLException e) {

    }   

    // second create table

        sql = "CREATE TABLE IF NOT EXISTS " + TABLE_SEED  

                + " (ID INTEGER PRIMARY KEY, ToyID INTEGER,ToySeed BLOB,ToyMemo TEXT);";  

        try {  

        mTestDatabase.execSQL(sql);  

        } catch (SQLException ex) {  

        }  

    Log.i("testSeedDB", "CreateSeedTable");

    }      

    public void CreateInfoTable() {  

    // first delete old table

    String sql = "drop table"+ TABLE_INFO;

    try {

        mTestDatabase.execSQL(sql);

    } catch (SQLException e) {

    }   

    // second create table

    sql = "CREATE TABLE IF NOT EXISTS " + TABLE_INFO  

                + " (ToyID INTEGER PRIMARY KEY,ToySeed BLOB,ToyMemo TEXT not null);";  

        try {  

        mTestDatabase.execSQL(sql);  

        } catch (SQLException ex) {  

        }  

    }      

   

    public void CleanSeedTable() {  

        try {  

        mTestDatabase.delete(TABLE_SEED, null, null);  

        } catch (SQLException e) {  

        } 

    Log.i("testSeedDB", "ClearSeedTable");        

    }      

   

    public void insertSeedItem(long ToyID, byte[]ToySeed) {  

    String sqlstr = "insert into " + TABLE_SEED + " (ToyID, ToySeed,ToyMemo) values (?,?,?);";

    Object[] args = new Object[]{ToyID,ToySeed,null};

        try{

        mTestDatabase.execSQL(sqlstr,args);  

        } catch (SQLException ex) {  

        }  

    Log.i("testSeedDB", "insertSeedItem");        

       

    }     

 

    public byte[] GetSeedItem(long ToyID) {  

    Cursor cur;

        byte[] strSeed = null;

   

        String col[] = {"ToyID", "ToySeed" ,"ToyMemo"};

        String strToy = "ToyID=" +  new Integer((int) ToyID).toString();

        try{

        cur = mTestDatabase.query(TABLE_SEED, col, strToy, null, null, null, null);

            cur.moveToFirst();

            strSeed = cur.getBlob(1);

        } catch (SQLException ex) {  

        }  

        if (cur !=null) cur.close;

        Log.i("testSeedDB", strToy);        

        return strSeed;

    }     

 

   // 数据操作的基础类,作为数据操作的内嵌子类

    public class testDBHelper extends SQLiteOpenHelper {

    public testDBHelper(Context context, String name, CursorFactory factory,

           int version) {

        super(context, name, factory, version);

        // TODO Auto-generated constructor stub

    }

 

    @Override

    public voidonCreate(SQLiteDatabase db) {

        // TODO Auto-generated method stub

    }

      @Override

    public voidonUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        // TODO Auto-generated method stub

    }

    }  // end of testDBHelper

}


// 读文件到 BYTE 来自网上 未验证

//http://www.a3gs.com/BookViews.asp?InfoID=2865&ClassID=935

 

导入包

 

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

 

实现代码

 

public class Test {

    public static void main(String[] args) {

       // TODO Auto-generated method stub

       try{

           getBytesFromFile(new File("C:\\aaa.txt"));

       }catch(IOException e){

           System.out.println("IOException");

       }

    }

    // 返回一个byte数组

    public static byte[] getBytesFromFile(File file) throws IOException {

        InputStream is = new FileInputStream(file);

 

        // 获取文件大小

        long length = file.length();

 

        if (length > Integer.MAX_VALUE) {

            // 文件太大,无法读取

        throw new IOException("File is to large "+file.getName());

        }

 

        // 创建一个数据来保存文件数据

        byte[] bytes = new byte[(int)length];

 

        // 读取数据到byte数组中

        int offset = 0;

        int numRead = 0;

        while (offset < bytes.length

               && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {

            offset += numRead;

        }

 

        // 确保所有数据均被读取

        if (offset < bytes.length) {

            throw new IOException("Could not completely read file "+file.getName());

        }

 

        // Close the input stream and return bytes

        is.close();

        return bytes;

    }

}