android本地数据库,微信数据库WCDB for Android 使用实例
Home · Tencent/wcdb Wiki
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 void onCreate(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(Listlist) { 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 getFavoritesListData() { List 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
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); } })); }