數(shù)據(jù)庫的使用

寫基類的APP類,用于承接上下文

public classAppextendsApplication {

     public staticAppappcontext;

 @Override

      public voidonCreate() {

       super.onCreate();

      appcontext=this;

    }

      }

建一個工具類

 //加上Static 代表只運(yùn)行一次,且只復(fù)制一次數(shù)據(jù)庫
 static{    copyDB();     }

 public static voidcopyDB() {

        InputStream input =null;

       FileOutputStream output =null;

       try{

      input = App.appcontext.getAssets().open("db/commonnum.db");

           File file =newFile(DB_PATH);

       if(!file.exists()) file.mkdirs();

       output =newFileOutputStream(DB_PATH+ File.separator+DB_NAME);

      intlen =0;

      byte[] buffer =new byte[1024];

      while((len = input.read(buffer)) != -1) {

        output.write(buffer,0,len);

   }

            }catch(IOException e) {

          e.printStackTrace();

         }finally{

         try{

       if(output !=null) output.close();

      if(input !=null) input.close();

              }catch(IOException e) {

         e.printStackTrace();

}
}
}

舉一個例子

  /**
 * 獲取所有的服務(wù)類型的名字
 *
 * @return
 */
public static List<Tel> getTelServiceName() {
    List<Tel> tels = new ArrayList<>();
    //獲取數(shù)據(jù)庫
    SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(DB_PATH + "/" + DB_NAME, null);
    //那個要查詢的數(shù)據(jù)庫的名字
    Cursor cursor = db.rawQuery("select * from classlist;", null);
    while (cursor.moveToNext()) {
       //重?cái)?shù)據(jù)庫查詢名字
        String name = cursor.getString(cursor.getColumnIndex("name"));
        //從數(shù)據(jù)庫找到對應(yīng)的ID
        int id = cursor.getInt(cursor.getColumnIndex("idx"));
        //自己的一個實(shí)例類
        Tel tel = new Tel(name, id);
        //添加到集合中
        tels.add(tel);
    }
    //關(guān)閉流,節(jié)省資源
    cursor.close();
    return tels;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,094評論 25 709
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,578評論 19 139
  • SQLite是一種嵌入式的數(shù)據(jù)庫引擎,最后是以文件的形式保存數(shù)據(jù)的,專門適用于資源有限的設(shè)備上進(jìn)行適量的數(shù)據(jù)存儲,...
    李俊的博客閱讀 3,720評論 0 8
  • swift開發(fā)需要應(yīng)用數(shù)據(jù)庫,fmdb筆記繁瑣,在swift中準(zhǔn)備放棄使用,看到了 Realm這個三方框架很強(qiáng)大,...
    Kean_Qi閱讀 7,203評論 9 12
  • 早上出門太急,
    左清晨閱讀 86評論 0 0

友情鏈接更多精彩內(nèi)容