很多项目都有用到数据库,最近学习了一下SQLiteOpenHelper的创建,下面是使用方法
创建一个Class DBHelper 继承 SQLiteOpenHelper
public class DBHelper extends SQLiteOpenHelper {
private static DBHelper dbHelper;
//类没有实例化,是不能用作父类构造器的参数,必须声明为静态
private static final String NAME = "SQLITE.db"; //数据库名称
private static final int version = 1; //数据库版本
public static final String TABLE_NAME = "person";//表名
/**
* 插入数据的的表名和一下字段
* */
private static final String TABLE_CREATE =
"CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(" +
"id INTEGER PRIMARY KEY AUTOINCREMENT," +
"name TEXT," +
"age TEXT," +
"sex TEXT)";
public DBHelper(Context context) {
super(context, NAME, null, version);
}
public static DBHelper getInstance(Context context) {
if (dbHelper == null) {
dbHelper = new DBHelper(context);
}
return dbHelper;
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(TABLE_CREATE);//创建表
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
插入数据
DBHelper helper = DBHelper.getInstance(this);
SQLiteDatabase database = helper.getWritableDatabase();//以写方式打开数据库
ContentValues values = new ContentValues();
values.put("name", "小王");
values.put("age", "25");
values.put("sex", "男");
database.insert(DBHelper.TABLE_NAME, null, values);//插入数据
database.close();//关闭SQLiteDatabase
查询数据
DBHelper helper = DBHelper.getInstance(MainActivity.this);
SQLiteDatabase database = helper.getReadableDatabase();//以读方式打开数据库
/**
* 查询全部的数据,在rawQuery中必须要加select * from
* 注意select * from 后面必须要有空格
* */
Cursor c = database.rawQuery("select * from "+DBHelper.TABLE_NAME, null);
/**
*增加查询条件 有汉字汉字必须加单引号
* */
// Cursor c = database.rawQuery("select * from " + DBHelper.TABLE_NAME
// + " where name = '小王' and age = 30", null);
while (c.moveToNext()) {
System.out.println(">>>>>>>>id>" + c.getString(c.getColumnIndex("id")));
System.out.println(">>>>>>>>name>" + c.getString(c.getColumnIndex("name")));
System.out.println(">>>>>>>>age>" + c.getString(c.getColumnIndex("age")));
System.out.println(">>>>>>>>sex>" + c.getString(c.getColumnIndex("sex")));
}
database.close();//关闭
删除插入的某一条数据
DBHelper helper = DBHelper.getInstance(this);
SQLiteDatabase database = helper.getWritableDatabase();//以写方式打开数据库
//删除插入的某一条数据
//"id = 2" :查询条件
database.delete(DBHelper.TABLE_NAME, "id = 2", null);
database.close();//查询完了要关闭SQLiteOpenHelper
修改某一条数据
DBHelper helper = DBHelper.getInstance(this);
SQLiteDatabase database = helper.getWritableDatabase();//以读写方式打开数据库
ContentValues values = new ContentValues();
values.put("name", "小里");
/**
* 修改插入的某一条数据 values必填
* "id = 6 and age = 30" :修改条件
* */
database.update(DBHelper.TABLE_NAME, values, "id = 6 and age = 30", null);
database.close();//查询完了要关闭SQLiteOpenHelper