1.首先需要一个类集成SQLiteOpenHelper
public class RecordSQLiteOpenHelper extends SQLiteOpenHelper {
//数据库名称
private static String name = "temp.db";
//数据库版本号
private static Integer version = 1;
public RecordSQLiteOpenHelper(Context context) {
super(context, name, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
//执行数据库创建表的语句
db.execSQL("create table records(id integer primary key autoincrement,name varchar(200))");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
2.在activity中声明变量
private RecordSQLiteOpenHelper helper = new RecordSQLiteOpenHelper(this);;
private SQLiteDatabase db;
3.插入数据
/**
* 插入数据
*/
private void insertData(String tempName) {
db = helper.getWritableDatabase();
db.execSQL("insert into records(name) values('" + tempName + "')");
db.close();
}
4.模糊查询数据
/**
* 模糊查询数据
*/
private void queryData(String tempName) {
Cursor cursor = helper.getReadableDatabase().rawQuery(
"select id as _id,name from records where name like '%" + tempName + "%' order by id desc ", null);
// 创建adapter适配器对象
adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor, new String[] { "name" },
new int[] { android.R.id.text1 }, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
// 设置适配器
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
5.查询数据库中是否有该条数据
/**
* 检查数据库中是否已经有该条记录
*/
private boolean hasData(String tempName) {
Cursor cursor = helper.getReadableDatabase().rawQuery(
"select id as _id,name from records where name =?", new String[]{tempName});
//判断是否有下一个
return cursor.moveToNext();
}
6.清空数据
/**
* 清空数据
*/
private void deleteData() {
db = helper.getWritableDatabase();
db.execSQL("delete from records");
db.close();
}