博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
android本地数据库,微信数据库WCDB for Android 使用实例
阅读量:4970 次
发布时间:2019-06-12

本文共 8592 字,大约阅读时间需要 28 分钟。

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(List
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
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() {            @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);                        }                    }));    }

 

转载于:https://www.cnblogs.com/zdz8207/p/android-local-wcdb.html

你可能感兴趣的文章
上周热点回顾(8.18-8.24)
查看>>
Feature toggle
查看>>
day02
查看>>
我是怎么招聘程序员的
查看>>
gvim 配置Pydiction
查看>>
Linux安装指定mysql版本
查看>>
Exception in thread "main" java.lang.ClassNotFoundException: 解决方法
查看>>
移动应用(手机应用)开发IM聊天程序解决方案
查看>>
[转载] K3漏油器全紫铜替换原硅胶垫教程。标准姿势
查看>>
python set
查看>>
VC中使用ADO操作数据库的方法
查看>>
如何判断域名是否被微信拦截 被已经被微信封了的的域名网址如何在微信中正常打开...
查看>>
分布式锁的三种实现方式
查看>>
AJAX原生JS代码
查看>>
ThinkPHP提示错误
查看>>
poj 2109 pow函数也能这么用?p的开n次方
查看>>
Oracle database link
查看>>
清北学堂2017NOIP冬令营入学测试P4749 F’s problem(f)
查看>>
POJ 1840 Eqs HASH
查看>>
python调用shell小技巧
查看>>