Android数据库操作

package com.xxx.app.common.util;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper4SP extends SQLiteOpenHelper
{
	
	private static final String DATABASE_NAME = "SharedPref.db";
	private static final int DATABASE_VERSION = 3;
	
	public static final String TABLE_NAME = "tb_sp";

	private static DBHelper4SP instance = null;

	public static synchronized DBHelper4SP getInstance(Context context)
	{
		if (instance == null) 
		{
			instance = new DBHelper4SP(context);
		}
		return instance;
	}

	private DBHelper4SP(Context context)
	{
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	private static String sql = "";
	static
	{
		sql = "CREATE TABLE " + TABLE_NAME + "("
				+ "id INTEGER PRIMARY KEY AUTOINCREMENT," 
				+ "key TEXT,"
				+ "value TEXT" + ")";
	}

	@Override
	public void onCreate(SQLiteDatabase db)
	{
		db.execSQL(sql);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
	{
		if (oldVersion < newVersion) 
		{
			db.execSQL("DROP TABLE if exists " + TABLE_NAME);
			
			db.execSQL(sql);
		}
	}

}

package com.xxxx.app.common.util;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DBTool4SP
{
	
	private final static String TAG = DBTool4SP.class.getCanonicalName();
	
	private static SQLiteDatabase sdb;

	private DBTool4SP() 
	{
		
	}
	
	private static DBTool4SP instance = new DBTool4SP();
	
	public static DBTool4SP getInstance(Context context) 
	{
		sdb = DBHelper4SP.getInstance(context).getWritableDatabase();
		return instance;
	}
	

	public void insert(String key, String value)
	{

		delete(key);

		try
		{
			ContentValues values = new ContentValues();
			values.put("key", key);
			values.put("value", value);
			sdb.insert(DBHelper4SP.TABLE_NAME, "id", values);
			
			Log4Debug.e(TAG, "insert (" + key + ", " + value + ")");
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

	}

	public void delete(String key)
	{

		try
		{
			sdb.delete(DBHelper4SP.TABLE_NAME, "key = ?", new String[] { key });
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

	}

	public String query(String key)
	{

		String value = "";

		try
		{
			Cursor c = sdb.query(DBHelper4SP.TABLE_NAME, null, "key = ?",
					new String[] { key }, null, null, null);
			while (c.moveToNext())
				value = c.getString(2);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		Log4Debug.e(TAG, "query (" + key + ", " + value + ")");

		return value;
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值