How to store an image file to SQliteDB in android

根据上一篇转载内容我自己尝试着把一个image文件存入到sqlite中,并且把它读出来。

    从数据库中读出的文件放在以下路径:/data/data/packagename/files。

    完整代码如下:

    

package com.test.image;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;

public class ImageStoreActivity extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
   
    private static final String DB_NAME = "mp3Song.db";
   
    private static final int DB_VERSION = 2;
   
    private Button btn, btn2, btn3;
   
    private Cursor cur;
   
    private MediaPlayer mPlayer;
   
    private static class DatabaseHelper extends SQLiteOpenHelper {
       
        DatabaseHelper(Context context) {
            super(context, DB_NAME, null, DB_VERSION);
        }
       
        @Override
        public void onCreate(SQLiteDatabase db) {
        }
       
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        }
       
    }
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setContentView(R.layout.main);
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
       
        btn = new Button(this);
        btn.setId(101);
        btn.setText("show");
        // btn.setBackgroundResource(resid);
        btn.setOnClickListener(this);
        LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(80, 50);
        param.topMargin = 10;
        layout.addView(btn, param);
        setContentView(layout);
       
        btn2 = new Button(this);
        btn2.setId(102);
        btn2.setText("retrieve");
        btn2.setOnClickListener(this);
        layout.addView(btn2, param);
       
        // init();
        setTitle("Saving into SQliteDB.");
    }
   
    private DatabaseHelper mOpenHelper;
   
    public void init() {
        mOpenHelper = new DatabaseHelper(this);
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        String sql_drop = "drop table IF EXISTS imagetable";
        db.execSQL(sql_drop);
       
        String sql_create = "create table imagetable("
                + "pic_id text not null, " + "pic_detail blob);";
        db.execSQL(sql_create);
       
        SaveOneSong(db, "s01", R.raw.beauty);
        db.close();
        setTitle("saved in SQLiteDB.");
    }
   
    public void SaveOneSong(SQLiteDatabase db, String key, int rid) {
        ContentValues cv = new ContentValues();
        cv.put("pic_id", key);
       
        InputStream ins = getResources().openRawResource(rid);
        byte[] buffer = new byte[63 * 1024];
        try {
            int size = ins.read(buffer);
            while (size > 0) {
                ByteArrayOutputStream out = new ByteArrayOutputStream(size);
                out.write(buffer, 0, size);
                out.flush();
                out.close();
               
                cv.put("pic_detail", out.toByteArray());
                db.insert("imagetable", null, cv);
                size = ins.read(buffer);
            }
        } catch (Exception e) {
           
        } finally {
            try {
                ins.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
       
    }
   
    private void retrieve(String cond) {
        FileOutputStream os = null;
        try {
            os = openFileOutput("xixi.jpg", MODE_WORLD_READABLE);
        } catch (Exception e) {
           
        }
        byte red_buf[];
        mOpenHelper = new DatabaseHelper(this);
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        String col[] = {"pic_id", "pic_detail"};
        Cursor c = db.query("imagetable", col, cond, null, null, null, null);
        int k = 0;
        c.moveToFirst();
        try {
            while (!c.isAfterLast()) {
                red_buf = c.getBlob(1);               
                os.write(red_buf);
                k++;
                c.moveToNext();
            }
            os.flush();
            os.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
    }
   
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case 101:
            init();
            break;
        case 102:
            retrieve("pic_id='s01'");
            break;
        }
    }
}

 

 

原文:http://xiaoxixi615.blog.sohu.com/142058403.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
I'm not sure which statement you're referring to, but assuming you have an SQLite database set up and you want to execute SQL statements on it, you can use a SQLite client or a programming language with a SQLite library to connect to the database and execute statements. Here are the general steps for using SQLite in a programming language: 1. Install a SQLite library for your programming language. Some popular ones include SQLite3 for Python, sqlite-jdbc for Java, and sqlite for Node.js. 2. Connect to the database using the library's API. This typically involves creating a connection object with the path to the database file and any other relevant connection information, such as credentials. 3. Execute SQL statements on the database using the connection object. This can be done with a variety of methods, depending on the library and programming language you're using. For example, in Python with the sqlite3 library, you can use the `execute` method of a connection object to run SQL statements. 4. Close the connection when you're finished working with the database. Here's an example of using the sqlite3 library in Python to execute a simple SQL statement: ```python import sqlite3 # Connect to the database conn = sqlite3.connect('example.db') # Execute a SQL statement conn.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)') # Close the connection conn.close() ``` This code creates a new SQLite database file called "example.db" and creates a new table called "users" with two columns, "id" and "name". The `execute` method is used to run the SQL statement. Finally, the connection is closed with the `close` method.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值