【Android】【xUtils3資料庫的簡單操作】
阿新 • • 發佈:2019-02-02
在xUtils3中對資料庫操作的封裝很好用,比常規的操作要簡單了很多,省去了很多程式碼。
使用這個功能需要建立一個與資料庫表對應的實體類,看程式碼
第一步:
@Table(name = "history_url")//表示資料中的資料表名
public class HistoryUrl {
@Column(name = "_id",isId = true)//表中的id列,name自定
private int id;
@Column(name = "url")//表中的url列
private String url;
}
第二步:
DAO資料庫操作類,我這裡只寫了增,查;
public class HistoryUrlDao { private final DbManager.DaoConfig daoConfig; public HistoryUrlDao() { daoConfig = new DbManager.DaoConfig()//配置 .setDbName("catch_picture.db")//資料庫名 .setDbVersion(1);//版本號 } /** * 獲取資料庫中所有資料 * @return 包含所有資料的集合 */ public List<HistoryUrl> getAll() {//這個集合裡的物件必須和定義好的資料庫表對應類一致 List<HistoryUrl> list = new ArrayList<>(); DbManager db = null; try { db = x.getDb(daoConfig);//獲取資料庫連線物件 list= db.findAll(HistoryUrl.class);//查詢表,如果沒有記錄,返回null } catch (DbException e) { e.printStackTrace(); } finally { if(db != null) { try { db.close(); } catch (IOException e) { e.printStackTrace(); } } if(list == null) {//為了防止資料庫中沒有資料而返回null造成的空指標 list = new ArrayList<>(); } } return list; } /** * 儲存一條資料到表中 */ public void save(HistoryUrl historyUrl) { DbManager db = null; try { db = x.getDb(daoConfig); db.saveBindingId(historyUrl);//加入資料到表中,將生成的id新增到物件中 } catch (DbException e) { e.printStackTrace(); } finally { if(db != null) { try { db.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
應該很容易看的懂!