SQlite数据库(4)---DAO(data access object)数据访问对象

SQlite数据库(1)
SQlite数据库(2)—-android 操作
SQlite数据库(3)—API操作

实现步骤

1.实体类

2.实体类DAO

public class BookDao extends SQLiteOpenHelper{
//私有保护
private static SQLiteDatabase db;
//公有静态方法获取db
    public static SQLiteDatabase getInstance(Context context){
        if(db == null){
            db = new BookDao(context).getReadableDatabase();
        }
        return db;
    }

    private BookDao(Context context){
        super(context, Environment.getExternalStorageDirectory() + "/book.db",null,1);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
}

public Cursor addBook(Book book){
    String sql="insert into 1_tb (name,type) values(?,?)";
    db.execSQL(sql,new String[]{book.getName(),book.getType()});

}
public void getBook(String...strs){
    String sql="select * from 1_tb ";
    if(strs.length!=0){
        sql+="where" + strs[0] + "='" +strs[1] +"'";
    }
    Cursor c=db.rawQuery(sql,null);
    return c;
}

public void deleteBook(String...strs){
    String sql="delete from 1_tb where "+strs[0]+"='"+strs[1]+"'";
    db.execSQL(sql); 

}
public void updateBook(BOOK bk){
    String sql="update info 1_tb set name=?,type=?";
    db.execSQL(sql,new objedt[]{bk.getName(),bk.getType()}); 
}

3.调用代码
第一种:对于可以实例化DAO类的获取dao.方法名
第二种:类名.getInstance 类名.方法名 静态方法

BookDao bd=new;
//查询同删除
String key="",value="";
if(mName.equals(""){
    key="name";
    value=mName;    
}
Cursor c;
if(key.equals("")){
    c=dao.getBook();
}else{
    c=dao.getBook(key,value);
}

用cursor 获取 arraylist

ArrayList<Book> list=new ArrayList<>();
Cursor c = //调用上面的getBook方法获得
while(c.moveToNext()){
    int id=c.getInt(0);
    String name=c.getString(1);
    String type=c.getString(2);
    Book book=new Book(id,name,type);
    list.add(book);
}

你可能感兴趣的