zoukankan      html  css  js  c++  java
  • android本地数据库,微信数据库WCDB for Android 使用实例

    android本地数据库,微信数据库WCDB for Android 使用实例

    Home · Tencent/wcdb Wiki
    https://github.com/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(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);
                            }
    
                        }));
    
    
        }
  • 相关阅读:
    数组构建完全二叉树
    [.net core学习] .net core中的MD5CryptoServiceProvider取代方法
    [.net core学习] .net core中的MD5CryptoServiceProvider取代方法
    [.net core学习] .net core中的MD5CryptoServiceProvider取代方法
    [.net core学习] .net core中的MD5CryptoServiceProvider取代方法
    交互式访问数据库
    Jackson /常用注解/ annotation
    vue图表组件使用,组件文档echarts
    java8 Optional 容器类
    java8 : Lambda 方法引用
  • 原文地址:https://www.cnblogs.com/zdz8207/p/android-local-wcdb.html
Copyright © 2011-2022 走看看