- 继承 SQLiteOpenHelper
- 创建某个“数据库操作类”
使用数据库操作类获取数据库并且进行相应的操作
一. 继承 SQLiteOpenHelper
public class DatabaseHelper extends SQLiteOpenHelper {
private Context mContext;
//建表语句
private String CREATE_SVHISTORY = "create table Searchhistory ("
+ "id integer primary key autoincrement ," + "name text,"
+ "sort integer)";
public DatabaseHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
mContext = context;
}
//onCreate方法只会执行一次,里面一般都是建表语句的执行
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_SVHISTORY);
Toast.makeText(mContext, "数据库创建成功", Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
}
//更新数据库时用到的方法,如果版本号不同则调用此方法。什么是版本号参考第二步
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
}
二. 创建某个“数据库操作类”
public class HistoryDB {
/**
* 数据库名
*/
private static final String DB_NAME="kanjianStore";
/**
* 数据库版本
*/
private static final int VERSION=1;
private static HistoryDB historyDB;
private SQLiteDatabase db;
/**
* 将构造方法私有化
*/
private HistoryDB(Context context) {
DatabaseHelper dbHeleper=new DatabaseHelper(context, DB_NAME, null, VERSION);
db=dbHeleper.getWritableDatabase();
}
/**
* 获取HistoryDB实例
*/
public synchronized static HistoryDB getInstance(Context context ){
if (historyDB==null) {
historyDB=new HistoryDB(context);
}
return historyDB;
}
/**
* 将搜索历史实例存储到数据库中
*/
public void saveHistory(SearchHistory searchHistory){
if(searchHistory!=null){
ContentValues values=new ContentValues();
values.put("name", searchHistory.getName());
values.put("sort", searchHistory.getSort());
db.insert("Searchhistory", null, values);
}
}
/**
* 从数据库中取出搜索记录
* @param sort 为1时取出所有视频搜索记录,为2时取出所有鉴客搜索记录
* @return
*/
public List<SearchHistory> loadSearchHistory(int sort){
List<SearchHistory> slist=new ArrayList<SearchHistory>();
/**
* 从数据库中取出搜索记录
* //查询语句,第一个参数是表名,第二个时列明 null表示全查,第
* 三第四个是条件,第五个是groupBy,第六个时having,第七个是 *orderby desc表示降序 asc表示升序,注意desc 和 asc 要有空格
* @return
*/
Cursor cursor =db.query("Searchhistory", null, "sort = ?", new String[]{String.valueOf(sort)}, null, null, "id"+" desc");
if(cursor.moveToFirst()){
do{
SearchHistory searchHistory=new SearchHistory();
searchHistory.setName(cursor.getString(cursor.getColumnIndex("name")));
slist.add(searchHistory);
}while (cursor.moveToNext());
}
if (cursor!=null) {
cursor.close();
}
return slist;
}
/**
* 删除历史记录
* @param sort 为1时删除视频搜索记录,为2时删除鉴客搜索记录
*/
public void deleteSearchHistory(int sort){
db.delete("Searchhistory", "sort = ?", new String[]{String.valueOf(sort)});
}
}
三. 使用数据库操作类获取数据库并且进行相应的操作
historyDB = HistoryDB.getInstance(this);
//加载搜索历史
historyList = historyDB.loadSearchHistory(1);