1 在DAO类内 定义一些链接数据库进行增删改查的方法
2 再定义一个DBHelper类继承于SQLiteOpenHelper 写构造方法 DBHelper( Context context ) { super ( context,"XXX.db", null, 1 ) } ----->>> 创建数据库
3 重写onCreate()方法 在方法中:
例如:public void onCreate(SQLiteDatabase db) {
String createSoftTable = " create table softinfo ( " +
" softid integer primary key autoincrement , " +
" softname text not null , " +
" softprice text , " +
" softjieshao text , " +
" softheat integer , " +
" softtypeid integer " +
" ) ";
db.execSQL(createSoftTable); //最后执行这个sql语句 创建数据库表
4 在DAO类中 首先 声明两个成员变量 SQLiteDatabase database, Context ctx;在写构造方法
public FenLeiDAO(Context ct){
ctx = ct;
}
5 在DAO类中 定义打开关闭数据库的方法
例://打开数据库
public void openDb(){
DBHelper dbHelper = new DBHelper(ctx);
database = dbHelper.getWritableDatabase(); //这个database 对象就是操作数据库的对象
}
//关闭数据库
public void closeDb(){
database.close();
Log.d("test","数据库关闭成功");
}
6 再在DAO类中 定义增删改查的方法
例://添加
public void addSoftType(String softtypename ,String softtypeshuxing){
String insertSoftType = "insert into softtype ( softtypename , softtypeshuxing ) values ( ?,? ) ";
database.execSQL(insertSoftType, new Object[]{softtypename,softtypeshuxing});
Log.d("test","数据插入成功");
}
//查询
public ArrayList<HashMap> findSoftTypeByCategory(String typename){
ArrayList<HashMap> alldatas = new ArrayList<HashMap>();
String selectSql = "select * from softtype where softtypeshuxing = ? ";
Cursor cur = database.rawQuery(selectSql, new String []{typename});
while(cur.moveToNext()){
HashMap hashMap = new HashMap();
hashMap.put("typename", cur.getString(cur.getColumnIndexOrThrow("softtypename")));
hashMap.put("typeshuxing", cur.getString(cur.getColumnIndexOrThrow("softtypeshuxing")));
alldatas.add(hashMap);
}
cur.close();
return alldatas;
}
public ArrayList<HashMap> findSoftTypeByCategory(){
ArrayList<HashMap> alldatas = new ArrayList<HashMap>();
String selectSql = "select * from softtype ";
Cursor cur = database.rawQuery(selectSql, null);
while(cur.moveToNext()){
HashMap hashMap = new HashMap();
hashMap.put("id", cur.getInt(cur.getColumnIndexOrThrow("id")));
hashMap.put("typename", cur.getString(cur.getColumnIndexOrThrow("softtypename")));
hashMap.put("typeshuxing", cur.getString(cur.getColumnIndexOrThrow("softtypeshuxing")));
alldatas.add(hashMap);
}
cur.close();
return alldatas;
}
//查询数据库中的 app属性 如:工具 生活 等 如果有就把他们添加到appinfo类中的spinner对象中
public ArrayList<HashMap> findTypeByCategory(){
ArrayList alldatas = new ArrayList();
String selectSql = "select softtypename from softtype ";
Cursor cur = database.rawQuery(selectSql,null);
while(cur.moveToNext()){
//HashMap hashMap = new HashMap();
alldatas.add(cur.getString(cur.getColumnIndexOrThrow("softtypename")));
//alldatas.add(hashMap);
}
cur.close();
return alldatas;
}
public boolean deleteAppType(int id){
boolean flag = true;
try {
database.delete("softtype", "id="+id, null);
} catch (Exception e) {
flag = false;
e.printStackTrace();
}
return flag;
}