android本地資料庫,微信資料庫WCDB for Android 使用例項
阿新 • • 發佈:2018-12-27
android本地資料庫,微信資料庫WCDB for Android 使用例項
WCDB是一個高效、完整、易用的移動資料庫框架,基於SQLCipher,支援iOS, macOS和Android。
編譯依賴項不是必要的,你完全可以使用預先編譯好的庫。
build.gradle 引入:
dependencies {
implementation 'com.tencent.wcdb:wcdb-android:1.0.2'
}
WCDB for Android
基本功能
基於SQLCipher的資料庫加密
使用連線池實現併發讀寫
內建 Repair Kit 可用於修復損壞資料庫
針對佔用空間大小優化的資料庫備份/恢復功能
日誌輸出重定向以及效能跟蹤介面
內建用於全文搜尋的 mmicu FTS3/4 分詞器
例項:
import android.content.Context; import com.tencent.wcdb.DatabaseErrorHandler; import com.tencent.wcdb.database.SQLiteDatabase; import com.tencent.wcdb.database.SQLiteOpenHelper; import java.io.File; class WcdbHelper extends SQLiteOpenHelper { private Context mContext;public WcdbHelper(Context context, String name, byte[] password, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) { super(context, name, password, factory, version, errorHandler); this.mContext = context; } @Override public voidonCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { LogUtil.i("db","oldVersion:" + oldVersion); LogUtil.i("db","newVersion:" + newVersion); } public boolean onDelete(String name) { File file = mContext.getDatabasePath(name); return SQLiteDatabase.deleteDatabase(file); } }
import android.content.ContentValues; import android.content.Context; import com.aax.exchange.entity.Favorites; import com.tencent.wcdb.Cursor; import com.tencent.wcdb.database.SQLiteDatabase; import java.util.ArrayList; import java.util.List; public class FavoritesDBManager { private WcdbHelper mDBHelper; private SQLiteDatabase mDB; private String name = "favorites.db"; private String password = "xxx"; public FavoritesDBManager(Context context) { mDBHelper = new WcdbHelper(context,name,password.getBytes(),null,1,null); mDB = mDBHelper.getWritableDatabase(); addTable(); } public boolean addFavoritesData(String tradingPair) { try { mDB.beginTransaction(); final String sql = "INSERT INTO favorites VALUES(NULL,?)"; Object[] objects = new Object[]{tradingPair}; mDB.execSQL(sql, objects); mDB.setTransactionSuccessful(); }catch (Exception e){ return false; }finally { mDB.endTransaction(); } return true; } public boolean addFavoritesData(Favorites favorites) { try { mDB.beginTransaction(); final String sql = "INSERT INTO favorites VALUES(NULL,?)"; Object[] objects = new Object[]{favorites.getTradingPair()}; mDB.execSQL(sql, objects); mDB.setTransactionSuccessful(); }catch (Exception e){ return false; }finally { mDB.endTransaction(); } return true; } public boolean addFavoritesList(List<Favorites> list) { try { mDB.beginTransaction(); for (Favorites favorites : list) { Object[] objects = new Object[]{favorites.getTradingPair()}; final String sql = "INSERT INTO favorites VALUES(NULL,?)"; mDB.execSQL(sql, objects); } mDB.setTransactionSuccessful(); } catch (Exception e) { return false; } finally { mDB.endTransaction(); } return true; } public boolean delFavoritesByTradingPair(String tradingPair) { try { mDB.beginTransaction(); mDB.delete("favorites","tradingPair=?",new String[]{tradingPair}); mDB.setTransactionSuccessful(); } catch (Exception e) { return false; } finally { mDB.endTransaction(); } return true; } public Favorites getFavoritesByTradingPair(String tradingPair){ String sql = "select * from favorites where tradingPair=?"; Cursor cursor = mDB.rawQuery(sql, new String[]{tradingPair}); while (cursor.moveToNext()){ Favorites favorites = new Favorites(); favorites.setTradingPair(cursor.getString(cursor.getColumnIndex("tradingPair"))); return favorites; } return null; } public List<Favorites> getFavoritesListData() { List<Favorites> listData = new ArrayList<>(); Cursor c = getAllFavoritesInfo(); while (c.moveToNext()) { Favorites favorites = new Favorites(); favorites.setTradingPair(c.getString(c.getColumnIndex("tradingPair"))); listData.add(favorites); } c.close(); return listData; } private Cursor getAllFavoritesInfo() { return mDB.rawQuery("SELECT * FROM favorites", null); } public boolean updateFavoritesByName(String tradingPair){ ContentValues values = new ContentValues(); values.put("tradingPair", tradingPair); int flag = mDB.update("favorites", values, "tradingPair=?", new String[]{tradingPair}); if (flag > 0) { return true; } else { return false; } } public void closeDB() { mDB.close(); } public Boolean deleteDatabase(String name) { return mDBHelper.onDelete(name); } public void deleteFavoritesData() { mDB.execSQL("DELETE FROM favorites;"); } public void addTable() { String SQL_CREATE = "CREATE TABLE IF NOT EXISTS favorites (_id INTEGER PRIMARY KEY AUTOINCREMENT , tradingPair VARCHAR(50) )"; mDB.execSQL(SQL_CREATE); } }
public class Favorites { private String tradingPair; public String getTradingPair() { return tradingPair; } public void setTradingPair(String tradingPair) { this.tradingPair = tradingPair; } }
public void addFavorites(CoinListInfo data,BaseBindingAdapter mAdapter,Context context){ LogUtil.i("wxh", "getQuote=" + data.getQuote() + " getBase=" + data.getBase()); subscribe(coinSearchActivity,Api.getApiService().addFavorites(data.getQuote() + data.getBase()), new ObserverResponseListener<Object>() { @Override public void onNext(Object o) { //ToastUtil.showLongToast("add favorites on next"); String tradingPair = data.getQuote() + data.getBase(); FavoritesDBManager fm = new FavoritesDBManager(context); Favorites fav = new Favorites(); fav.setTradingPair(tradingPair); //if exits set true or set false if(data.isFavorite.get()){ data.isFavorite.set(Boolean.FALSE); fm.delFavoritesByTradingPair(tradingPair); }else{ data.isFavorite.set(Boolean.TRUE); fm.addFavoritesData(fav); } mAdapter.notifyDataSetChanged(); } @Override public void onError(Throwable e) { ToastUtil.showLongToast("add favorites error"); } }, coinSearchActivity.bindToLifecycle()); }
private void setSearch() { mCompositeDisposable.add(RxTextView.textChanges(mBinding.etSearchKey) .debounce(300, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .map(CharSequence::toString) .subscribe(s -> { //這裡可以查詢資料庫或請求伺服器查詢 if (!TextUtils.isEmpty(s.trim())){ searchList.clear(); FavoritesDBManager fm = new FavoritesDBManager(CoinSearchActivity.this); for (CoinListInfo item: mCoinSearchViewModel.data) { if (item.getQuote().contains(s.toUpperCase()) || item.getBase().contains(s.toUpperCase())){ String tradingPair = item.getQuote() + item.getBase(); Favorites fav = fm.getFavoritesByTradingPair(tradingPair); if(null != fav){ item.isFavorite.set(Boolean.TRUE); } searchList.add(item); } } mAdapter.setFilterData(searchList); }else{ mAdapter.setFilterData(null); } })); }