SQLite多线程读写

android sqlite多线程读写 在项目中需要用到多线程操作数据库, 阅读详情

           前天去某某公司面试,被问到SQLite的多线程读写问题,突然发现都没注意到这个问题,翻了下以前做的项目,发现很少注意到这个问题,奇葩的是貌似很少出现过问题啊 = =!但是这个android.database.sqlite.SQLiteException: database is locked异常确实前几天在公司项目中出现过几次,后来就进行了研究总结,现在分享出来,水平有限,不妥或者错误的地方还望指出。

    SQLite实质上是将数据写入一个文件,通常情况下,在应用的包名下面都能找到xxx.db的文件,拥有root权限的手机,可以通过adb shell,看到data/data/packagename/databases/xxx.db这样的文件。我们可以联系到另外一个关系型数据库H2,其实两者还是有很多相似的地方的,此处就不详细介绍H2了。

    由此我们可以得知SQLite其实是文件级别的锁:多个线程可以同时读,但是同时只能有一个线程写。Android提供了SqliteOpenHelper类,加入Java的锁机制以便调用。如果多线程同时读写(注意:指的是不同的线程用使用不同的SqliteOpenHelper实例),后面的操作就会遇到android.database.sqlite.SQLiteException: database is locked这样的异常。很显然,解决这种问题就必须保持SQLite Connection的单例性,即保持始终只有一个SQLite连接实例,并且需要对所有的数据库操作方法加sychronized关键字,如下代码:

    

public class MyDatabaseHelper extends SQLiteOpenHelper {
        public static final String TAG = "MyDatabaseHelper";
        private static final String DB_NAME = "test.db";
        private static final int DB_VERSION = 1;

        private Context mContext;
        private static MyDatabaseHelper mInstance;

        private MyDatabaseHelper(Context context) {
                super(context, DB_NAME, null, DB_VERSION);
        }

        public synchronized static MyDatabaseHelper getInstance(Context context) {
                if (mInstance == null) {
                        mInstance = new MyDatabaseHelper(context);
                }
                return mInstance;
        }
        public synchronized static void destoryInstance() {
              if (mInstance != null) {
                    mInstance.close();
             }
       }
        @Override
        public void onCreate(SQLiteDatabase db) {
                // TODO Auto-generated method stub

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                // TODO Auto-generated method stub

        }
        public synchronized void queryMethod() {
                SQLiteDatabase readableDatabase = getReadableDatabase();
                //read operation
        }
        
        public synchronized void updateMethod() {
                SQLiteDatabase writableDatabase = getWritableDatabase();
                //update operation
        }
}
   Android为我们提供了SqliteOpenHelper类,通过getWritableDatabase或者getReadableDatabase可以拿到SQLiteDatabase对象,然后执行相关方法。这2个方法名称太容易给人误解,我自己也在很长的一段时间内想当然的认为getReadabeDatabase就是获取一个只读的数据库,可以获取很多次,多个线程同时读,用完就关闭,查看了Google源码,才发现实际上getReadableDatabase先以读写方式打开数据库,如果数据库的磁盘空间满了,就会打开失败,当打开失败后会继续尝试以只读方式打开数据库。

    SqliteOpenHelper.java:

 

/**
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
 
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.util.Log;
 
/***
 * A helper class to manage database creation and version management.
 * You create a subclass implementing {@link #onCreate}, {@link #onUpgrade} and
 * optionally {@link #onOpen}, and this class takes care of opening the database
 * if it exists, creating it if it does not, and upgrading it as necessary.
 * Transactions are used to make sure the database is always in a sensible state.
 * <p>For an example, see the NotePadProvider class in the NotePad sample application,
 * in the <em>samples/</em> directory of the SDK.</p>
 */
public abstract class SQLiteOpenHelper {
    private static final String TAG = SQLiteOpenHelper.class.getSimpleName();
 
    private final Context mContext;
    private final String mName;
    private final CursorFactory mFactory;
    private final int mNewVersion;
 
    private SQLiteDatabase mDatabase = null;
    private boolean mIsInitializing = false;
 
    /***
     * Create a helper object to create, open, and/or manage a database.
     * The database is not actually created or opened until one of
     * {@link #getWritableDatabase} or {@link #getReadableDatabase} is called.
     *
     * @param context to use to open or create the database
     * @param name of the database file, or null for an in-memory database
     * @param factory to use for creating cursor objects, or null for the default
     * @param version number of the database (starting at 1); if the database is older,
     *     {@link #onUpgrade} will be used to upgrade the database
     */
    public SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version) {
        if (version < 1) throw new IllegalArgumentException("Version must be >= 1, was " + version);
 
        mContext = context;
        mName = name;
        mFactory = factory;
        mNewVersion = version;
    }
 
    /***
     * Create and/or open a database that will be used for reading and writing.
     * Once opened successfully, the database is cached, so you can call this
     * method every time you need to write to the database.  Make sure to call
     * {@link #close} when you no longer need it.
     *
     * <p>Errors such as bad permissions or a full disk may cause this operation
     * to fail, but future attempts may succeed if the problem is fixed.</p>
     *
     * @throws SQLiteException if the database cannot be opened for writing
     * @return a read/write database object valid until {@link #close} is called
     */
    public synchronized SQLiteDatabase getWritableDatabase() {
        if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) {
            return mDatabase;  // The database is already open for business
        }
 
        if (mIsInitializing) {
            throw new IllegalStateException("getWritableDatabase called recursively");
        }
 
        // If we have a read-only database open, someone could be using it
        // (though they shouldn't), which would cause a lock to be held on
        // the file, and our attempts to open the database read-write would
        // fail waiting for the file lock.  To prevent that, we acquire the
        // lock on the read-only database, which shuts out other users.
 
        boolean success = false;
        SQLiteDatabase db = null;
        if (mDatabase != null) {
            mDatabase.lock();
        }
        try {
            mIsInitializing = true;
            if (mName == null) {
                db = SQLiteDatabase.create(null);
            } else {
                db = mContext.openOrCreateDatabase(mName, 0, mFactory);
            }
 
            int version = db.getVersion();
            if (version != mNewVersion) {
                db.beginTransaction();
                try {
                    if (version == 0) {
                        onCreate(db);
                    } else {
                        onUpgrade(db, version, mNewVersion);
                    }
                    db.setVersion(mNewVersion);
                    db.setTransactionSuccessful();
                } finally {
                    db.endTransaction();
                }
            }
 
            onOpen(db);
            success = true;
            return db;
        } finally {
            mIsInitializing = false;
            if (success) {
                if (mDatabase != null) {
                    try { mDatabase.close(); } catch (Exception e) { }
                    mDatabase.unlock();
                }
                mDatabase = db;
            } else {
                if (mDatabase != null) mDatabase.unlock();
                if (db != null) db.close();
            }
        }
    }
 
    /***
     * Create and/or open a database.  This will be the same object returned by
     * {@link #getWritableDatabase} unless some problem, such as a full disk,
     * requires the database to be opened read-only.  In that case, a read-only
     * database object will be returned.  If the problem is fixed, a future call
     * to {@link #getWritableDatabase} may succeed, in which case the read-only
     * database object will be closed and the read/write object will be returned
     * in the future.
     *
     * @throws SQLiteException if the database cannot be opened
     * @return a database object valid until {@link #getWritableDatabase}
     *     or {@link #close} is called.
     */
    public synchronized SQLiteDatabase getReadableDatabase() {
        if (mDatabase != null && mDatabase.isOpen()) {
            return mDatabase;  // The database is already open for business
        }
 
        if (mIsInitializing) {
            throw new IllegalStateException("getReadableDatabase called recursively");
        }
 
        try {
            return getWritableDatabase();
        } catch (SQLiteException e) {
            if (mName == null) throw e;  // Can't open a temp database read-only!
            Log.e(TAG, "Couldn't open " + mName + " for writing (will try read-only):", e);
        }
 
        SQLiteDatabase db = null;
        try {
            mIsInitializing = true;
            String path = mContext.getDatabasePath(mName).getPath();
            db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY);
            if (db.getVersion() != mNewVersion) {
                throw new SQLiteException("Can't upgrade read-only database from version " +
                        db.getVersion() + " to " + mNewVersion + ": " + path);
            }
 
            onOpen(db);
            Log.w(TAG, "Opened " + mName + " in read-only mode");
            mDatabase = db;
            return mDatabase;
        } finally {
            mIsInitializing = false;
            if (db != null && db != mDatabase) db.close();
        }
    }
 
    /***
     * Close any open database object.
     */
    public synchronized void close() {
        if (mIsInitializing) throw new IllegalStateException("Closed during initialization");
 
        if (mDatabase != null && mDatabase.isOpen()) {
            mDatabase.close();
            mDatabase = null;
        }
    }
 
    /***
     * Called when the database is created for the first time. This is where the
     * creation of tables and the initial population of the tables should happen.
     *
     * @param db The database.
     */
    public abstract void onCreate(SQLiteDatabase db);
 
    /***
     * Called when the database needs to be upgraded. The implementation
     * should use this method to drop tables, add tables, or do anything else it
     * needs to upgrade to the new schema version.
     *
     * <p>The SQLite ALTER TABLE documentation can be found
     * <a href="http://sqlite.org/lang_altertable.html">here</a>. If you add new columns
     * you can use ALTER TABLE to insert them into a live table. If you rename or remove columns
     * you can use ALTER TABLE to rename the old table, then create the new table and then
     * populate the new table with the contents of the old table.
     *
     * @param db The database.
     * @param oldVersion The old database version.
     * @param newVersion The new database version.
     */
    public abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);
 
    /***
     * Called when the database has been opened.
     * Override method should check {@link SQLiteDatabase#isReadOnly} before
     * updating the database.
     *
     * @param db The database.
     */
    public void onOpen(SQLiteDatabase db) {}
}
   由于数据库文件打开后会加锁,必须等前面的关闭后后面的调用才能正常执行,所以我们可以有one Write+Many Read(有可能产生冲突,因为第一个getReadableDatabase有可能先于getWritableDatabase执行,导致后面的失败),也可以Many Read,但是不可能Many Write。故单例加上同步的数据库操作方法,就不会出现死锁的问题。

SQLite的多线程应用与iOS开发 对于SQLiite支持多线程的问题,我找到一片很不错的文章: http://www.keakon.net/2011/10/25/SQLite%E5%9C%A8%E5%A4%9A%E7%BA%BF%E7%A8%8B%E7%8E%AF%E5%A2%83%E4%B8%8B%E7%9A%84%E5%BA%94%E7%94%A8 。  文章很长,需要有耐心的读一下。  1. 对于多个进程可以同时打 阅读详情

相关推荐

Sqlite关于多线程的研究

研究流程 缓存需求 缓存场景多样化与缓存方案的统一 网络请求的多线程场景导致sqlite多线程问题 sqlite多线程问题的解决方案 单例(Singleton)或者sychronized——读读同步,读写同步,写写同步 非单例(多读、一写)——读读并发,读写同步,写写同步 非单例(多读,一写)——读读并发,读写并发,写写同步 非单例(多读,多写)——读读并发,读写并发,写写并发 Refer 一、

m_xiaoer的博客 1054

SQLite多线程并发操作

SQLite多线程并发操作 先理清楚一个概念 多线程操作和多数据库连接操作是不同的概念 多线程操作:多线程操作数据库时可以使用一个数据库连接,也可以每个线程使用各自的数据库连接 多数据库连接操作:即每个数据库操作使用的是各自的数据库连接 SQLite默认情况下只支持单个数据库连接操作,多连接并发操作时会出问题,需要开启wal模式才能进行多项城并发读操作,写操作仍能不可以并发。 ...

邑大丶捷的博客 2万+

C#多线程读写sqlite

多线程读写sqlite数据库,同步锁,计时测试读写性能,

SQLITE和多线程

sqlite支持三种不同的线程模式: 1)单线程single-thread。这种模式中,所有的互斥锁都失效,并且sqlite超过一个线程就不能安全的使用。 2)多线程multi-thread。这种模式中,sqlite可以安全的被多个线程使用,假如此时在两个或者更多线程中同时使用不止一个database的连接。 3)串行化serialized。在串行化模式中,sqlite可以不受限制的使用安全

chinaclock的专栏 5899

ARTIX-7 GTP 3G-SDI 工程构建与调试实战

本文详细介绍了基于ARTIX-7 FPGA和GTP收发器的3G-SDI工程构建与调试实战。从基础概念解析到Vivado工程创建、GTP IP核配置、SDI IP核集成,再到系统集成与时钟域处理,提供了全面的技术指导。文章还分享了调试技巧、常见问题排查方法以及性能验证步骤,帮助开发者快速掌握3G-SDI视频传输技术的实现与优化。

weixin_30443813的博客 267

Python爬虫实战:用BeautifulSoup和Pandas轻松抓取去哪儿网景点数据(附完整代码)

本文详细介绍了如何使用Python的BeautifulSoup和Pandas库构建一个高效的旅游数据爬虫,从去哪儿网抓取景点数据。内容涵盖环境准备、网页结构分析、核心代码实现、反爬策略以及数据清洗与存储,提供完整代码示例,帮助开发者快速掌握数据采集技术。

river的博客 364

Android基础之 SQLite多线程读写实践及常见问题总结

基本操作的部分,大家都很熟悉了,这里根据个人切身经验,总结了一些经常遇到的,也需要注意的一些问题,与大家分享,水平有限,不妥或者错误的地方还望指出。 多线程读写 SQLite实质上是将数据写入一个文件,通常情况下,在应用的包名下面都能找到xxx.db的文件,拥有root权限的手机,可以通过adb shell,看到data/data/packagename/databases/xxx.db这样...

qq_17085163的博客 1414

【论文复现】自动化细胞核分割与特征分析

HoVer-Net是一种精心设计的多分支深度学习网络架构,专为处理复杂的多组织显微图像中的细胞核实例分割与精确分类任务而开发。该网络通过创新的策略,不仅有效解决了细胞核在密集聚集区域难以准确区分的问题,还实现了对每个独立细胞核类型的细致分类。此外,HoVer-Net还引入了专门的上采样分支,这一设计旨在对每个成功分割出的细胞核实例进行进一步的核类型分类。这一分支利用高级语义信息,结合精心设计的分类策略,能够准确判断每个细胞核的所属类型,为医学研究提供了宝贵的细胞水平信息。

2201_75366661的博客 1986

C多线程读写sqlite

C#多线程读写sqlite 去发现同类优质开源项目:https://gitcode.com/ 此仓库提供了一个C#编写的多线程读写sqlite数据库的示例代码,通过使用同步锁来保证数据的一致性和完整性。代码中包含了计时测试,用于评估多线程环境下读写SQLite数据库的性能表现。适用于希望了解和深入研究多线程操作SQLite数据库的开发者学习和使用。 去发现同类优质开源项目:https://git...

gitblog_06735的博客 345

上证指数30年k线图_金融占星简单解读上证指数30年历史行情

阅读此文需要一定的占星基础知识,本人对于金融知识了解甚少,如有描述错误请包涵指正!影响大众事件发展趋势的都是外行星,即木星-冥王星这5颗,由于时间跨度长达30年,绘制社会行星的K线图工作量太大,所以只以时代行星对这30年行情的简单解读作为分享,在今后的短期分析中会逐渐加入社会行星,甚至在个股分析上还会加入个人行星。那即使只绘制时代行星,所展现出来的信息也无法在一张图上画出来,否则太乱难以分辨,所以...

weixin_39831242的博客 1685

Windows 10 下 DockerToolbox 安装全攻略:从下载到配置阿里云镜像加速

本文详细介绍了在Windows 10系统上安装和配置DockerToolbox的完整流程。从下载安装包、执行初步安装,到关键步骤——修改虚拟机存储路径以及配置阿里云镜像加速器,旨在帮助开发者,尤其是初次接触Docker的新手,快速搭建高效的本地容器开发环境,并解决国内镜像下载缓慢的痛点。

moon9的博客 483

SQLite多线程读写实践

基本操作的部分,大家都很熟悉了,这里根据个人切身经验,总结了一些经常遇到的,也需要注意的一些问题,与大家分享,水平有限,不妥或者错误的地方还望指出。 多线程读写 SQLite实质上是将数据写入一个文件,通常情况下,在应用的包名下面都能找到xxx.db的文件,拥有root权限的手机,可以通过adb shell,看到data/data/packagename/databases

Hknock的专栏 3457

PyTorch视觉项目实战:从数据加载到模型部署

PyTorch视觉项目实战:从数据加载到模型部署 ,人工智能,计算机视觉,大模型,AI,随着深度学习在计算机视觉领域的飞速发展,PyTorch 凭借其简洁的代码风格、动态计算图特性以及强大的社区支持,成为众多开发者和研究人员的首选框架。从数据加载、模型构建与训练,到最终的模型部署,PyTorch 提供了一套完整且灵活的解决方案。本文将通过实际项目案例,详细阐述基于 PyTorch 的视觉项目全流程,结合丰富的代码示例和概念解析,帮助读者掌握从项目起步到落地的关键技术。

不踩坑,不知道坑有多深;不总结,踩过的坑白踩。 4万+

解决IOS多线程读写Sqlite问题解决

http://www.cnblogs.com/likwo/archive/2012/04/09/2438790.html 现在ios里使用的数据库一般都是Sqlite,但是使用Sqlite有个不太好的地方就是在多线程的时候,会出现问题,sqlite只能打开一个读或者写连结。这样的话多线程就会碰到资源占用的问题。   最开始是使用FMDB,FMDB的早期版本不能解决这个问题,后

qian521kun521的专栏 478

UE5接入在线直播视频源,如hls(m3u8)格式

UE5接入在线直播视频源

专注GIS开发 9528

4、基于抽象解释的静态分析器中的跟踪分区与ASTRÉE分析器解析

本博客探讨了基于抽象解释的静态分析器中的跟踪分区技术,并深入解析了ASTRÉE分析器的工作原理和应用。通过示例程序说明了跟踪分区如何提升分析精度,减少误报,以及ASTRÉE如何利用多种数值抽象域(如八角形域、浮点区间线性形式等)来处理复杂的嵌入式C程序。此外,还讨论了ASTRÉE的模块化设计、循环展开优化、用户断言与自动细化的局限性等内容,为保障嵌入式软件的安全性和可靠性提供了理论与实践支持。

kotlin6android的博客 121

C多线程读写sqlite:提升数据库性能的利器

C#多线程读写sqlite:提升数据库性能的利器 去发现同类优质开源项目:https://gitcode.com/ 在当今软件开发领域,数据库操作的高效性直接影响着应用程序的性能。C#多线程读写sqlite项目正是为了解决这一问题而诞生的。以下,我们将详细了解这一项目的核心功能、技术分析、应用场景以及项目特点。 项目介绍 C#多线程读写sqlite项目是一个开源示例代码仓库,专门为C#开发者提供了...

gitblog_06709的博客 1167

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

SQlite多线程读写

转载于:http://bbs.51cto.com/thread-990260-1.html 多线程读写     SQLite实质上是将数据写入一个文件,通常情况下,在应用的包名下面都能找到xxx.db的文件,拥有root权限的手机,可以通过adb shell,看到data/data/packagename/databases/xxx.db这样的文件。 我们可以得知SQLite是文件级别的锁

style_in的专栏 1592

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

利用读写锁实现sqlite多线程写的问题

之前项目中利用sqlite存储解析后的数据,网上的资料并没有找到sqlite本身机制对于多线程如何支持,所以就利用每个线程一个库,最后在合并,今天看到读写锁SRWLOCK时,决定尝一下解决多线程写sqlite的问题如愿解决:    测试代码    main函数中:sqlite3_open_v2("test.db",&amp;m_db,SQLITE_OPEN_CREATE|SQLITE_OPEN_R...

小郑的博客 6084

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

SQLite多线程读写实践及常见问题总结

基本操作的部分,大家都很熟悉了,这里根据个人切身经验,总结了一些经常遇到的,也需要注意的一些问题,与大家分享,水平有限,不妥或者错误的地方还望指出。 多线程读写 SQLite实质上是将数据写入一个文件,通常情况下,在应用的包名下面都能找到xxx.db的文件,拥有root权限的手机,可以通过adb shell,看到data/data/packagename/databases

changwilling的博客 2754

IOS多线程读写Sqlite问题解决

现在ios里使用的数据库一般都是Sqlite,但是使用Sqlite有个不太好的地方就是在多线程的时候,会出现问题,sqlite只能打开一个读或者写连结。这样的话多线程就会碰到资源占用的问题。   最开始是使用FMDB,FMDB的早期版本不能解决这个问题,后来FMDB更新了,新版本的FMDB能够很好的解决这个多线程使用Sqlite 。 FMDB github网址  https://

ffblog的专栏 593
上一篇: 土司蛋挞
下一篇: 那些年,我们常见的那些人
Ronys
博客等级 码龄17年 206粉丝 122原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值