package cn.reciteWord.operation;
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;
/*
* 创建数据库
*/
public class MyDataBaseAdapter {
public static String DB_NAME = "vocabulary.db";
public static String ID = "_id";
public static String CHA = "chinese";
public static String ENG = "english";
private static String tableName = "vocabulary";
private static int version = 1;
private static final String DB_CREATE = "CREATE TABLE IF NOT EXISTS " + tableName + " (" + ID + " INTEGER PRIMARY KEY," + CHA + " TEXT," + ENG + " TEXT)";
private Context mContext = null;
private SQLiteDatabase mSqLiteDatabase = null;//保存返回的数据库对象
private DataBaseHelper mDataBaseHelper = null;
private static class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, version );
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(DB_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// 删除以前的旧表,创建一张新的空表
db.execSQL("DROP TABLE IF EXISTS " + DB_NAME);
onCreate(db);
}
}
public MyDataBaseAdapter(Context context) {
// TODO Auto-generated constructor stub
mContext = context;
}
//打开数据库, 返回数据库对象
public void open() throws SQLException{
mDataBaseHelper = new DataBaseHelper(mContext);
}
//关闭数据库
public void close() {
mDataBaseHelper.close();
}
public long insertData(String en, String ch) {
// 插入数据
mSqLiteDatabase = mDataBaseHelper.getWritableDatabase();
ContentValues mContentValues = new ContentValues();
mContentValues.put(ENG, en);
mContentValues.put(CHA, ch);
return mSqLiteDatabase.insert(tableName, ID, mContentValues);
}
public boolean deleteData(long rowID) {
// 删除一条数据
mSqLiteDatabase = mDataBaseHelper.getWritableDatabase();
return mSqLiteDatabase.delete(tableName, ID + "=" + rowID, null) > 0;
}
public Cursor fetchAllData() {
//查询所有数据
mSqLiteDatabase = mDataBaseHelper.getWritableDatabase();
return mSqLiteDatabase.query(tableName, new String[] {ID, ENG, CHA}, null, null, null, null, null);
}
public Cursor fetchData(long rowID)throws SQLException {
mSqLiteDatabase = mDataBaseHelper.getWritableDatabase();
Cursor cursor = mSqLiteDatabase.query(true, tableName, new String[] {ID, ENG, CHA}, ID + "=" + rowID, null, null, null, null, null);
if(cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public boolean updateData(long rowId, String en, String ch) {
//更新一条数据
mSqLiteDatabase = mDataBaseHelper.getWritableDatabase();
ContentValues mContentValues = new ContentValues();
mContentValues.put(ENG, en);
mContentValues.put(CHA, ch);
return mSqLiteDatabase.update(tableName, mContentValues, ID + "=" + rowId, null) > 0;
}
}