Android 内存数据库

在android中数据库通常以文件的形式存储在磁盘中,而内存数据库是将数据驻留在内存中,因此可以作为一种缓存技术方案。 那么在android如何使用sqlite的内存数据库呢?

看SQLiteDatabase的源码:

/**
     * Create a memory backed SQLite database.  Its contents will be destroyed
     * when the database is closed.
     *
     * <p>Sets the locale of the database to the  the system's current locale.
     * Call {@link #setLocale} if you would like something else.</p>
     *
     * @param factory an optional factory class that is called to instantiate a
     *            cursor when query is called
     * @return a SQLiteDatabase object, or null if the database can't be created
     */
    public static SQLiteDatabase create(CursorFactory factory) {
        // This is a magic string with special meaning for SQLite.
        return openDatabase(MEMORY_DB_PATH, factory, CREATE_IF_NECESSARY);
    }

CREATE_IF_NECESSARY 表示:当数据库不存在时将被创建。  通过方法注释可以知道此方法可以创建内存数据库,并当数据库关闭时数据将被清除。

另外一种方法,请看SQLiteOpenHelper源码:

public synchronized SQLiteDatabase getWritableDatabase() {
        
        boolean success = false;
        SQLiteDatabase db = null;
        if (mDatabase != null) mDatabase.lock();
        try {
            mIsInitializing = true;
            if (mName == null) {
                db = SQLiteDatabase.create(null);
            } else {
                db = mContext.openOrCreateDatabase(mName, 0, mFactory, mErrorHandler);
            }

            ...

            onOpen(db);
            success = true;
            return db;
        } finally {
            mIsInitializing = false;
            if (success) {
                if (mDatabase != null) {
                    try { mDatabase.close(); } catch (Exception e) { }
                    mDatabase.unlock();
                }
                mDatabase = db;
            } else {
                if (mDatabase != null) mDatabase.unlock();
                if (db != null) db.close();
            }
        }
    }

从代码中可以知道,当mName(数据库名称)为null时,将创建内存数据库。

我写了一个demo请看代码:

package dw.test;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.provider.BaseColumns;
import android.util.Log;

public final class MemoryDbTester {
	
	private static final String LOG_TAG = MemoryDbTester.class.getSimpleName();
	private static final String TABLE_NAME = "t_user";
	private SQLiteDatabase mMemoryDb;
	
	private MemoryDbTester(){
		mMemoryDb = createMemoryDb();
	}
	
	private static MemoryDbTester sDefault = new MemoryDbTester();
	
	public static MemoryDbTester getDefault(){
		return sDefault;
	}
	
	public interface Columns extends BaseColumns {
		public static final String UNAME = "uname";
	}
	
	/**
	 * 创建内存数据库
	 */
	private SQLiteDatabase createMemoryDb(){
		SQLiteDatabase database = SQLiteDatabase.create(null);
		String t_user_sql = "CREATE TABLE "+TABLE_NAME+"(_id integer primary key autoincrement,"+Columns.UNAME+" varchar(10))";
		database.execSQL(t_user_sql);
		return database;
	}
	/**
	 * 向内存数据库中插入一条数据
	 */
	public void testInsert() {
		
		SQLiteDatabase db = mMemoryDb;
		
		check(db);
		
		ContentValues values = new ContentValues();
		values.put(Columns.UNAME, "dw");
		
		db.insert(TABLE_NAME, null, values);
		
	}
	/**
	 * 查询内存数据库中的数据
	 */
	public void testQuery(){
		
		SQLiteDatabase db = mMemoryDb;
		
		check(db);
		
		Cursor c = db.rawQuery("select uname from t_user", null);
		
		while(c.moveToNext()){
			String name = c.getString(0);
			Log.i(LOG_TAG, "NAME:" + name);
		}
		
	}
	@Override
	protected void finalize() throws Throwable {
		
		releaseMemory();
		
		super.finalize();
	}
	
	public void releaseMemory(){
		SQLiteDatabase db = mMemoryDb;
		if(db!=null){
			db.close();
			mMemoryDb = null;
		}
	}
	
	private void check(SQLiteDatabase db) {
		if(db==null || !db.isOpen()){
			throw new IllegalStateException("memory database already closed");
		}
	}

}




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值