Android-sqlite数据库存取图片信息

看到网上很多人都用下面的几种方式保存图片到数据据,感觉蛮靠谱的,之前我转载的那些方法貌似都不管用(也可能是我不会用),今晚先收藏,明天或者有空的时候再试试下面的方法,先收藏:

更新

SQLiteDatabase db;
  String args[] = {id};
  ContentValues cv = new ContentValues();

  cv.put("android123", id);
  Cursor c = db.rawQuery("SELECT * FROM table WHERE android123=?", args); 执行本地SQL语句查询

  if (c.getCount() != 0) {
  //dosomething

  ContentValues cv = new ContentValues();

  cv.put("android123","cwj");
  db.insert("table", "android123", cv);  //插入数据

  String args[] = {id};
  ContentValues cv2= new ContentValues();

  cv2.put("android123", id);
  db.delete("table", "android123=?", args); //删除数据

  }





网上第一个版本:
一、数据库创建和存取方法:

在数据库创建时,图片字段的数据类型存储为 BLOB数据库插入操作
public void onCreate(SQLiteDatabase db)
{
String sql = "create table " + TB_NAME + " ( " + ID + " integer primary key , " + IMAGE + " BLOB ) ";
db.execSQL(sql);
}

将图片一字节形式存储数据库读取操作
public long insert(byte[] img) 
{
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(IMAGE, img);
long result = db.insert(TB_NAME, null, cv);
return result;
}


得到的图片是Bitmap类型,参数position 点击图片在ListView、GridView等内的位置 ,可根据需要编写代码二
public Bitmap getBmp(int position) 
{
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = select(TB_NAME);
cursor.moveToPosition(position);
byte[] in = cursor.getBlob(cursor.getColumnIndex(IMAGE));
Bitmap bmpout = BitmapFactory.decodeByteArray(in, 0, in.length);
return bmpout;
}

二、将图片转化为 byte[]//参数id为图片资源 (R.drawable.img)
public byte[] img(int id)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap bitmap = ((BitmapDrawable) getResources().getDrawable(id)).getBitmap();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();

}

可惜我想要的是能一连串的查询,查询的时候有文字和图片一起都查到, 上面这种暂时不是我想要的,

下面这个人的感觉蛮可以,他应该是验证过的, 应该是我想要了的吧,

网上第二个版本

转自http://blog.sina.com.cn/s/blog_539070ad0100nesa.html

 

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 {

    privateContext mContext= null

    privatetestDBHelper mDBHelper= null

    privateSQLiteDatabase mTestDatabase= null

 

    privatestatic finalString DATABASE_NAME= "DHSeedData.db" 

    privatestatic finalint DATABASE_VERSION= 1;  

    privatestatic finalString TABLE_SEED= "TBseed" 

    privatestatic finalString TABLE_INFO= "TBinfo";  

 

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

    publictestSeedDB(Context context){ 

       mContext = context; 

    }

    // 打开数据库  

    publicvoid open(){

        mDBHelper= newtestDBHelper(mContext,DATABASE_NAME,null,DATABASE_VERSION); 

        mTestDatabase= mDBHelper.getWritableDatabase(); 

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

   

    // Close the database

    publicvoid close(){ 

         mDBHelper.close(); 

    }  

   

    publicvoid 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");

        

    publicvoid 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) {  

        

        

   

    publicvoid CleanSeedTable() {  

       try  

       mTestDatabase.delete(TABLE_SEED,null,null);  

        }catch (SQLException e) {  

       

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

        

   

    publicvoid insertSeedItem(longToyID, 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");        

       

       

 

    publicbyte[] GetSeedItem(longToyID) {  

    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;

       

 

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

    publicclass testDBHelperextends SQLiteOpenHelper {

    publictestDBHelper(Context context, String name, CursorFactory factory,

          int version) {

       super(context, name, factory, version);

       // TODOAuto-generated constructor stub

    }

 

    @Override

    publicvoidonCreate(SQLiteDatabase db) {

       // TODOAuto-generated method stub

    }

      @Override

    publicvoidonUpgrade(SQLiteDatabase db,int oldVersion, int newVersion) {

       // TODOAuto-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;

    }

}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值