Android在Sqlite3中的应用及多线程使用数据库的建议


Posted in Java/Android onApril 24, 2022

1、首先先建立一个DatabaseHelper类,继承自SQLiteOpenHelper,用于建立数据库,并可更新数据库例如我新建了两张表

public class DatabaseHelper extends SQLiteOpenHelper {

    private static DatabaseHelper _databaseHelper;
    private static final String TAG = DatabaseHelper.class.getSimpleName();
    public synchronized static DatabaseHelper getInstance(Context context)
    {
        if(_databaseHelper==null)
        {
            _databaseHelper = new DatabaseHelper(context,"cgjlb",null,2);
        }
        return _databaseHelper;
    }
    public synchronized static void destoryInstance(){
        if(_databaseHelper!=null){
            _databaseHelper=null;
    public DatabaseHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        //主表记录
        String sql = "create table t_share(_id integer primary key autoincrement,sharenum text,sharename text,shareprice real,sharelastprice real,addtime text,uptime text,bl real)";
        sqLiteDatabase.execSQL(sql);
        //记录历史表
        sql = "create table t_sharehis(_id integer primary key autoincrement,shareid integer, shareprice real,uptime text)";
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        Log.d(TAG, "onUpgrade: upddatabase");
        sqLiteDatabase.execSQL("drop table t_share");
        sqLiteDatabase.execSQL("drop table t_sharehis");
        onCreate(sqLiteDatabase);
}

2、编写数据库具体操作类、增删改查我都写了

public class ShareDbService {

    SQLiteDatabase db = null;
    DatabaseHelper databaseHelper;
    private static final String TAG = ShareDbService.class.getSimpleName();
    public ShareDbService(Context context) {
        databaseHelper = DatabaseHelper.getInstance(context);
        db = databaseHelper.getWritableDatabase();
    }
    public void addShareInfo(ShareBean shareBean)
    {
        int Id = getShareId(shareBean.getShareNum());
        if(Id==-1) {
            ContentValues values = new ContentValues();
            values.put("sharenum", shareBean.getShareNum());
            values.put("sharename", shareBean.getShareName());
            values.put("shareprice", shareBean.getSharePrice());
            values.put("sharelastprice", shareBean.getShareLastPrice());
            values.put("uptime", shareBean.getUptime());
            values.put("addtime",shareBean.getAddtime());
            double shareprice = shareBean.getSharePrice();
            double sharelastprice = shareBean.getShareLastPrice();
            double bl = (sharelastprice-shareprice)/shareprice*100;
            values.put("bl", new DecimalFormat("0.00").format(bl));
            db = databaseHelper.getWritableDatabase();
            db.insert("t_share", null, values);
            ShareHisBean shareHisBean = new ShareHisBean();
            shareHisBean.setShareId(getShareId(shareBean.getShareNum()));
            shareHisBean.setSharePrice(shareBean.getSharePrice());
            shareHisBean.setUpTime(shareBean.getUptime());
            addShareHis(shareHisBean);
            db.close();
        }
    private void addShareHis(ShareHisBean shareHisBean){
        ContentValues values = new ContentValues();
        values.put("shareid", shareHisBean.getShareId());
        values.put("shareprice", shareHisBean.getSharePrice());
        values.put("uptime", shareHisBean.getUptime());
        db.insert("t_sharehis", null, values);
        db.close();
    public void refreshShare(ShareHisBean shareHisBean,double sharePrice){
        try {
            //更新信息主表
            values.put("uptime", shareHisBean.getUptime());
            values.put("sharelastprice", shareHisBean.getSharePrice());
            String[] args = {String.valueOf(shareHisBean.getShareId())};
            double sharelastprice = shareHisBean.getSharePrice();
            double bl = (sharelastprice - sharePrice) / sharePrice * 100;
            values.put("bl", bl);
            db.update("t_share", values, "_Id=?", new String[]{String.valueOf(shareHisBean.getShareId())});
            //添加记录
            values = new ContentValues();
            values.put("shareid", shareHisBean.getShareId());
            values.put("shareprice", shareHisBean.getSharePrice());
            db.insert("t_sharehis", null, values);
        }catch(Exception ex){
            ex.printStackTrace();
        finally {
    public void delShare(String Id){
        db.delete("t_share","_Id=?",new String[]{Id});
        db.delete("t_sharehis","shareid=?",new String[]{Id});
    private int getShareId(String shareNum) {
        db = databaseHelper.getReadableDatabase();
        String sql = "select _Id from t_share where sharenum='" + shareNum + "'";
        int Id = -1;
        Cursor cursor = db.rawQuery(sql, null);
        if (cursor != null) {
            while (cursor.moveToNext()){
                Id = cursor.getInt(0);
            }
        cursor.close();
        return Id;
    public List<ShareBean> getShareList(){
        List<ShareBean> shareBeans = new ArrayList<>();
        String sql = "select _id,sharenum,sharename,shareprice,sharelastprice,uptime,addtime,bl from t_share order by _Id desc";
                ShareBean shareBean = new ShareBean();
                shareBean.set_Id(cursor.getInt(0));
                shareBean.setShareNum(cursor.getString(1));
                shareBean.setShareName(cursor.getString(2));
                shareBean.setSharePrice(cursor.getDouble(3));
                shareBean.setShareLastPrice(cursor.getDouble(4));
                shareBean.setUptime(cursor.getString(5));
                shareBean.setAddtime(cursor.getString(6));
                shareBean.setBl(cursor.getDouble(7));
                shareBeans.add(shareBean);
        return shareBeans;
    public List<ShareHisBean> getShareListHis(int ShareId){
        List<ShareHisBean> shareHisBeans = new ArrayList<>();
        String sql = "select _id,shareid,shareprice,uptime from t_sharehis where shareid='"+String.valueOf(ShareId)+"' order by _id desc";
                ShareHisBean shareHisBean = new ShareHisBean();
                shareHisBean.set_Id(cursor.getInt(0));
                shareHisBean.setShareId(cursor.getInt(1));
                shareHisBean.setSharePrice(cursor.getDouble(2));
                shareHisBean.setUpTime(cursor.getString(3));
                shareHisBeans.add(shareHisBean);
        return shareHisBeans;
    public ShareBean getShareInfo(int ShareId) {
        ShareBean shareBean = new ShareBean();
        //_id integer primary key autoincrement,sharenum text,sharename text,shareprice real,sharelastprice real,addtime text,uptime text,bl real
        String sql = "select _id,sharenum,sharename,shareprice,sharelastprice,addtime,uptime,bl from t_share where _Id='"+String.valueOf(ShareId)+"'";
            if (cursor.moveToNext()){
                shareBean.setAddtime(cursor.getString(5));
                shareBean.setUptime(cursor.getString(6));
        return shareBean;
}

3、实际中的应用,就举一个例子吧,数据库操作不用开新线程,直接在主线程里弄就行

ShareDbService shareDbService = new ShareDbService(getContext());
 shareDbService.delShare(String.valueOf(shareBean.get_Id()));

4、需要注意的是SQLite不支持多线程,最好是能批量修改,否则很麻烦,如果一定要多线程 ,比如循环请求网络更新数据库时,可以使用CountDownLatch,先将数据弄在一个集合里,等子线程全部执行完成后,再更新数据库。此方法具体应用如下

先声明一个变量

CountDownLatch latch;

实际应用代码

//设置多线程 个数,一共用多少个线程一定要写清楚,后面是要减的。
        latch = new CountDownLatch(count);
        for (int i = 0; i < count; i++) {            
            new Thread(()-> {
                try {
                    //网络请求等操作
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    //这里会自动减1操作,一定要写。
                    latch.countDown();
                }
            }).start();
        };
        try {
            latch.await();
           //最后执行主程序,比如更新数据库
            Toast.makeText(getContext(), "刷新成功", Toast.LENGTH_SHORT).show();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

到此这篇关于Android在Sqlite3中的应用及多线程使用数据库的建议的文章就介绍到这了!


Tags in this post...

Java/Android 相关文章推荐
SpringCloud Alibaba 基本开发框架搭建过程
Jun 13 Java/Android
浅析NIO系列之TCP
Jun 15 Java/Android
新手入门Jvm-- JVM对象创建与内存分配机制
Jun 18 Java/Android
详解Java实现数据结构之并查集
Jun 23 Java/Android
浅谈resultMap的用法及关联结果集映射
Jun 30 Java/Android
Java 语言中Object 类和System 类详解
Jul 07 Java/Android
springboot集成springCloud中gateway时启动报错的解决
Jul 16 Java/Android
mybatis源码解读之executor包语句处理功能
Feb 15 Java/Android
Spring Boot 底层原理基础深度解析
Apr 03 Java/Android
Java 垃圾回收超详细讲解记忆集和卡表
Apr 08 Java/Android
Android开发之底部导航栏的快速实现
Apr 28 Java/Android
springboot+rabbitmq实现智能家居实例详解
Jul 23 Java/Android
Android开发 使用文件储存的方式保存QQ密码
Apr 24 #Java/Android
IDEA 2022 Translation 未知错误 翻译文档失败
Android开发实现极为简单的QQ登录页面
Flutter Navigator 实现路由传递参数
Apr 22 #Java/Android
SpringBoot 集成短信和邮件 以阿里云短信服务为例
Java设计模式之代理模式
Apr 22 #Java/Android
Java工作中实用的代码优化技巧分享
Apr 21 #Java/Android
You might like
PHP数组对比函数,存在交集则返回真,否则返回假
2011/02/03 PHP
PHP封装curl的调用接口及常用函数详解
2018/05/31 PHP
js中将多个语句写成一个语句的两种方法小结
2007/12/08 Javascript
DOM下的节点属性和操作小结
2009/05/14 Javascript
IE6 弹出Iframe层中的文本框“经常”无法获得输入焦点
2009/12/27 Javascript
jQuery技巧总结
2011/01/01 Javascript
IE下JS读取xml文件示例代码
2013/08/05 Javascript
Jquery跳到页面指定位置的方法
2014/05/12 Javascript
jQuery实现移动端滑块拖动选择数字效果
2015/12/24 Javascript
Bootstrap编写一个兼容主流浏览器的受众门户式风格页面
2016/07/01 Javascript
浅谈JS对html标签的属性的干预以及对CSS样式表属性的干预
2017/06/25 Javascript
React-Native实现ListView组件之上拉刷新实例(iOS和Android通用)
2017/07/11 Javascript
纯js实现页面返回顶部的动画(超简单)
2017/08/10 Javascript
js实现数组和对象的深浅拷贝
2017/09/30 Javascript
javascript中new Array()和var arr=[]用法区别
2017/12/01 Javascript
小程序显示弹窗时禁止下层的内容滚动实现方法
2019/03/20 Javascript
微信小程序如何调用json数据接口并解析
2019/06/29 Javascript
element-ui树形控件后台返回的数据+生成组织树的工具类
2020/03/05 Javascript
基于Python Shell获取hostname和fqdn释疑
2016/01/25 Python
Python自定义一个类实现字典dict功能的方法
2019/01/19 Python
Python Django框架实现应用添加logging日志操作示例
2019/05/17 Python
在Pycharm中调试Django项目程序的操作方法
2019/07/17 Python
浅谈Selenium+Webdriver 常用的元素定位方式
2021/01/13 Python
html5 canvas实现跟随鼠标旋转的箭头
2016/03/11 HTML / CSS
最便宜促销价格订机票:Airpaz(总部设在印尼,支持中文)
2018/11/13 全球购物
英国奢侈品牌时尚购物平台:Farfetch(支持中文)
2020/02/18 全球购物
为数据库创建索引都需要注意些什么
2012/07/17 面试题
会计实习期自我鉴定
2013/10/06 职场文书
个人简历中的自我评价怎么写
2014/01/26 职场文书
物资采购方案
2014/06/12 职场文书
会计专业求职信
2014/08/10 职场文书
护士节演讲稿开场白
2014/08/25 职场文书
指导教师推荐意见
2015/06/05 职场文书
婚宴父亲致辞
2015/07/27 职场文书
2020年个人安全保证书参考模板
2020/01/08 职场文书
Python获取指定日期是"星期几"的6种方法
2022/03/13 Python