package com.king.android.db;
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;
/**
* 描述:数据库。。。
* 作者:Andy.Liu
* 时间: 2012-8-2 下午10:37:27
**/
public class MyDataBaseAdapter {
private static final String TAG = "MyDataBaseAdapter";
private Context mContext = null;
public static final String KEY_ID = "_id";
public static final String KEY_NUM = "num";
public static final String KEY_DATA = "data";
private static final String DB_NAME = "king.db";
private static final String TABLE_KING = "king";
private static final int DB_VERSION = 1;
//创建表的语句
private static final String CREATE_TAB_KING = null;
//执行open()打开数据库,保存返回的数据库对象
private SQLiteDatabase mSQlLiteDatabase = null;
//由SQLiteOpenHelper继承过来
private DatabaseHelper mDatabaseHelper = null;
//继承SQLiteOpenHelper
private static class DatabaseHelper extends SQLiteOpenHelper{
//构造函数创建数据库
public DatabaseHelper(Context context) {
/**
* 当调用getWriteableDatabase(),getReadableDatabase()方法时则创建一个数据库
*/
super(context, DB_NAME, null, DB_VERSION);
}
@Override/*创建数据表*/
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TAB_KING);
}
@Override//升级数据库
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS notes");
onCreate(db);
}
}
//构造函数取得Context
public MyDataBaseAdapter(Context context){
this.mContext = context;
}
//打开数据库,返回数据库对象
public void open()throws SQLException{
mDatabaseHelper = new DatabaseHelper(mContext);
mSQlLiteDatabase = mDatabaseHelper.getWritableDatabase();
}
//关闭数据库
public void close(){
mDatabaseHelper.close();
}
//插入一条数据
public long insertData(int num,String data){
ContentValues initValues = new ContentValues();
initValues.put(KEY_NUM, num);
initValues.put(KEY_DATA, data);
return mSQlLiteDatabase.insert(TABLE_KING, KEY_ID, initValues);
}
//删除一条数据
public boolean deleteData(long rowId){
return mSQlLiteDatabase.delete(TABLE_KING, KEY_ID + "="+ rowId, null)>0;
}
//通过Cursor查询所有数据
public Cursor fetchAllData(){
return mSQlLiteDatabase.query(TABLE_KING, new String[]{KEY_ID,KEY_NUM,KEY_DATA}, null, null, null, null, null);
}
//查询指定数据
public Cursor fetchData(long rowId){
Cursor mCursor = mSQlLiteDatabase.query(true, TABLE_KING, new String[]{KEY_ID,KEY_NUM,KEY_DATA}, KEY_ID+ "="+rowId, null, null, null,null,null);
if(null!=mCursor){
mCursor.moveToFirst();
}
return mCursor;
}
//更新一条数据
public boolean updateData(long rowId,int num,String data){
ContentValues args = new ContentValues();
args.put(KEY_NUM, num);
args.put(KEY_DATA, data);
return mSQlLiteDatabase.update(TABLE_KING, args, KEY_ID+ "="+rowId, null)>0;
}
}