sqlite数据库简单封装:
每一张表 都会对应一个Bean 和一个Dao类
sqliteHelper 主要负责创建数据库和更新数据库 主要为其提供 创建表的sql语句 数据库名称 和数据库版本号
- sqliteHelper类
public class sqliteHelper extends sqliteOpenHelper {
private static String DB_NAME="gac.db";
private static int VERSION = 1;
private static final String USER_TABLE_CREATE="create table if not exists "
+UserDao.TABLE_NAME +" ("
+UserDao.COLUMN_ID +" INTEGER PRIMARY KEY AUTOINCREMENT,"
+UserDao.COLUMN_NAME+" TEXT)";
private Context context;
private static sqliteHelper instance;
public static sqliteHelper getInstance(Context context){
if(instance == null){
instance = new sqliteHelper(context.getApplicationContext());
}
return instance;
}
public sqliteHelper(Context context){
super(context,DB_NAME,null,VERSION);
this.context = context;
}
public Context getContext(){
return context;
}
@Override
public void onCreate(sqliteDatabase db) {
db.execsql(USER_TABLE_CREATE);
}
@Override
public void onUpgrade(sqliteDatabase db,int oldVersion,int newVersion) {
}
public void closeDB(){
if(instance != null){
try{
sqliteDatabase db = instance.getWritableDatabase();
db.close();
}catch (Exception e){
e.printStackTrace();
}
instance = null;
}
}
}
- bean类主要负责 对应表 成员变量最好和表的字段名对应
public class UserBean {
public String name;
public int id;
public UserBean(){
}
public UserBean(String name){
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
4.dao类主要负责操作对应的表的增删该查 以及存储表的字段名 和表的名称 添加的数据可以利用反射进行操作
public class UserDao { public static String TABLE_NAME = "user"; public static String COLUMN_ID = "id"; public static String COLUMN_NAME = "name"; private sqliteHelper helper = null; public UserDao(Context context){ helper = new sqliteHelper(context); } //根据cursor获取userbean private UserBean getUserBeanByCursor(Cursor cursor){ UserBean user = new UserBean(); Class< ? extends UserBean> clazz = user.getClass(); Field[] fields = clazz.getDeclaredFields(); for(Field field :fields){ if(field.getName().equals("id")){ user.id = cursor.getInt(cursor.getColumnIndex("id")); continue; } if(field.getName().equals("name")){ user.name = cursor.getString(cursor.getColumnIndex("name")); continue; } } return user; } //根据user获取contentvalues private ContentValues getContentValues(UserBean user){ ContentValues values = new ContentValues(); Class<? extends UserBean> clazz = user.getClass(); try{ Method[] methods = clazz.getMethods(); Object[] args = null; for(Method method : methods) { String mName = method.getName(); if (mName.startsWith("get") && !mName.startsWith("getClass")) { String filedName = mName.substring(3,mName.length()).toLowerCase(); Log.e("gac","fieldName:"+filedName); if(filedName.equals("id")){ //id 让它自动增加 continue; } Object value = method.invoke(user,args); if (value instanceof String) { values.put(filedName,(String) value); } else if (value instanceof Integer) { values.put(filedName,(Integer) value); } } } }catch (Exception e){e.printStackTrace();} return values; } //添加用户 public boolean addUser(UserBean user){ boolean flag = false; sqliteDatabase database = null; long id = -1; try{ database = helper.getWritableDatabase(); ContentValues values = getContentValues(user); Class<? extends UserBean> calzz = user.getClass(); String tableName = TABLE_NAME; id = database.insert(tableName,null,values); flag = (id !=-1?true:false); if(database != null){ database.close(); } }catch (Exception e){ e.printStackTrace(); } Log.e("gac","addUser flag:"+flag); return flag; } //删除用户 public boolean delteUser(String id,String name){ boolean flag = false; String wereClause = "id = ? and name = ?"; String [] whereArgs = new String[]{id,name}; sqliteDatabase db = helper.getWritableDatabase(); try{ int res = db.delete(TABLE_NAME,wereClause,whereArgs); flag = (res != 0?true:false); if(db != null){ db.close(); } }catch (Exception e){ e.printStackTrace(); } return flag; } //更新数据库 public boolean updateUser(String whereClause,String[] whereArgs,UserBean user){ // String wereClause = "id = ? and name = ?"; // String [] whereArgs = new String[]{id,name}; boolean flag = false; sqliteDatabase db = helper.getWritableDatabase(); try{ ContentValues values = getContentValues(user); int res = db.update(TABLE_NAME,values,whereClause,whereArgs); flag = (res <= 0?false:true); db.close(); }catch (Exception e){e.printStackTrace();} Log.e("gac","updateUser:"+flag); return flag; } //查询 public List<UserBean> getUserList(String sql,String[] whereArgs){ sqliteDatabase db = helper.getWritableDatabase(); Cursor cursor = db.rawQuery(sql,whereArgs); List<UserBean> mList = null; if(cursor != null){ mList = new ArrayList<>(); while (cursor.moveToNext()){ mList.add(getUserBeanByCursor(cursor)); } } return mList; } }
- //测试例子
//new UserDao(this).addUser(new UserBean("gac"));
// new UserDao(this).updateUser("id = ?",new String[]{1+""},new UserBean("gac1"));
List<UserBean> list = new UserDao(this).getUserList("select * from " + UserDao.TABLE_NAME,null);
for(int i =0; i < list.size(); i++){
Log.e("gac",list.get(i).getName());
Log.e("gac",list.get(i).getId()+"");
}
原文链接:https://www.f2er.com/sqlite/198933.html