Kotlin 封装 DB 操作举例

首先继承SQLiteOpenHelper类,建一个自己的BaseDbHelper.kt

class BaseDbHelper(context: Context) : SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) {

    private val TAG = BaseDbHelper::class.java!!.getSimpleName()

    companion object {
        private val DB_NAME = "account.db"
        private val DB_VERSION = 6
    }

    override fun onCreate(db: SQLiteDatabase) {
        db.execSQL(UserTable.TABLE_SQL)
    }

    /**
     * onUpgrade()方法在数据库版本每次发生变化时都会把用户手机上的数据库表删除,然后再重新创建。<br></br>
     * 一般在实际项目中是不能这样做的,正确的做法是在更新数据库表结构时,还要考虑用户存放于数据库中的数据不会丢失,从版本几更新到版本几。(非
     * Javadoc)
     */
    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
        if (db != null && newVersion > oldVersion) {
            try {
                when (oldVersion) {
                    1 -> {
                        run {
                            addAccountAvatarColumn(db)
                            Log.d(BaseDbHelper::class.java!!.getSimpleName(), "[onUpgrade] 1 update db, oldVersion = " + oldVersion)
                        }
                        run {
                            //CREATE TABLE Account ( userId TEXT PRIMARY KEY, flyme TEXT, phone TEXT, nickName TEXT NOT NULL, icon TEXT);
                            db.execSQL("drop table if exists account_address")
                            Log.d(BaseDbHelper::class.java!!.getSimpleName(), "[onUpgrade] 2 update db, oldVersion = " + oldVersion)
                        }
                        run {
                            addAccountAreaCodeColumn(db)//添加国家码一栏
                            db.execSQL("drop table if exists account_address")
                            Log.d(BaseDbHelper::class.java!!.getSimpleName(), "[onUpgrade] 3 update db, oldVersion = " + oldVersion)
                        }
                        run {
                            addAccountEmailColumn(db)//添加邮件
                            db.execSQL("drop table if exists account_address")
                            Log.d(BaseDbHelper::class.java!!.getSimpleName(), "[onUpgrade] 4 update db, oldVersion = " + oldVersion)
                        }
                        run { addBackgroundImageColumn(db) }
                        Log.d(BaseDbHelper::class.java!!.getSimpleName(), "[onUpgrade] update db, oldVersion = " + oldVersion)
                    }
                    2 -> {
                        run {
                            db.execSQL("drop table if exists account_address")
                            Log.d(BaseDbHelper::class.java!!.getSimpleName(), "[onUpgrade] 2 update db, oldVersion = " + oldVersion)
                        }
                        run {
                            addAccountAreaCodeColumn(db)
                            db.execSQL("drop table if exists account_address")
                            Log.d(BaseDbHelper::class.java!!.getSimpleName(), "[onUpgrade] 3 update db, oldVersion = " + oldVersion)
                        }
                        run {
                            addAccountEmailColumn(db)
                            db.execSQL("drop table if exists account_address")
                            Log.d(BaseDbHelper::class.java!!.getSimpleName(), "[onUpgrade] 4 update db, oldVersion = " + oldVersion)
                        }
                        run { addBackgroundImageColumn(db) }
                        Log.d(BaseDbHelper::class.java!!.getSimpleName(), "[onUpgrade] update db, oldVersion = " + oldVersion)
                    }
                    3 -> {
                        run {
                            addAccountAreaCodeColumn(db)
                            db.execSQL("drop table if exists account_address")
                            Log.d(BaseDbHelper::class.java!!.getSimpleName(), "[onUpgrade] 3 update db, oldVersion = " + oldVersion)
                        }
                        run {
                            addAccountEmailColumn(db)
                            db.execSQL("drop table if exists account_address")
                            Log.d(BaseDbHelper::class.java!!.getSimpleName(), "[onUpgrade] 4 update db, oldVersion = " + oldVersion)
                        }
                        run { addBackgroundImageColumn(db) }
                        Log.d(BaseDbHelper::class.java!!.getSimpleName(), "[onUpgrade] update db, oldVersion = " + oldVersion)
                    }
                    4 -> {
                        run {
                            addAccountEmailColumn(db)
                            db.execSQL("drop table if exists account_address")
                            Log.d(BaseDbHelper::class.java!!.getSimpleName(), "[onUpgrade] 4 update db, oldVersion = " + oldVersion)
                        }
                        run { addBackgroundImageColumn(db) }
                        Log.d(BaseDbHelper::class.java!!.getSimpleName(), "[onUpgrade] update db, oldVersion = " + oldVersion)
                    }
                    5 -> {
                        run { addBackgroundImageColumn(db) }
                        Log.d(BaseDbHelper::class.java!!.getSimpleName(), "[onUpgrade] update db, oldVersion = " + oldVersion)
                    }
                }
            } catch (e: Exception) {
            }

        }
    }

    override fun onDowngrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
        if (db != null && oldVersion > newVersion) {
            var cursor: Cursor? = null
            try {
                cursor = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null)
                val tableNames = ArrayList<String>()
                if (cursor != null && cursor.moveToFirst()) {
                    do {
                        val name = cursor.getString(0)
                        if (!TextUtils.isEmpty(name) && !name.equals("android_metadata", ignoreCase = true)) {
                            tableNames.add(name)
                        }
                    } while (cursor.moveToNext())
                }
                if (tableNames.size > 0) {
                    for (name in tableNames) {
                        db.execSQL("DROP TABLE IF EXISTS " + name)
                    }
                }
                onCreate(db)
            } catch (e: Exception) {
            } finally {
                if (cursor != null) {
                    cursor.close()
                }
            }
        }
    }

    private fun addAccountAvatarColumn(db: SQLiteDatabase) {
        try {
            db.execSQL("ALTER TABLE " + UserTable.TABLE_NAME + " ADD COLUMN "
                    + UserTable.AVATAR_ICON + " TEXT;")
        } catch (e: Exception) {
            Log.e(TAG, "[addAccountAvatarColumn] error = " + e.message)
        }

    }

    private fun addAccountAreaCodeColumn(db: SQLiteDatabase) {
        try {
            db.execSQL("ALTER TABLE " + UserTable.TABLE_NAME + " ADD COLUMN "
                    + UserTable.COUNTRY_CODE + " TEXT;")
        } catch (e: Exception) {
            Log.e(TAG, "[addAccountAreaCodeColumn] error = " + e.message)
        }

    }

    private fun addAccountEmailColumn(db: SQLiteDatabase) {
        try {
            db.execSQL("ALTER TABLE " + UserTable.TABLE_NAME + " ADD COLUMN "
                    + UserTable.EMAIL + " TEXT;")
        } catch (e: Exception) {
            Log.e(TAG, "[addAccountEmailColumn] error = " + e.message)
        }

    }

    private fun addBackgroundImageColumn(db: SQLiteDatabase) {
        try {
            db.execSQL("ALTER TABLE " + UserTable.TABLE_NAME + " ADD COLUMN "
                    + UserTable.BACKGROUND_IMAGE + " TEXT;")
        } catch (e: Exception) {
            Log.e(TAG, "[addBackgroundImageColumn] error = " + e.message)
        }

    }
}

然后是新建一个单例CoreDBManager.kt,用来业务调用操作数据库增删改查等

class CoreDBManager private constructor(context: Context) {

    private var mDataBase: SQLiteDatabase? = null
    private val mBaseDbHelper: BaseDbHelper
    private val mOpenCounter = AtomicInteger()

    companion object {

        private val TAG = CoreDBManager::class.java!!.getSimpleName()
        @Volatile private var mInstance: CoreDBManager? = null

        fun getInstance(context: Context): CoreDBManager? {
            if (mInstance == null) {
                synchronized(CoreDBManager::class.java) {
                    if (mInstance == null) {
                        mInstance = CoreDBManager(context)
                    }
                }
            }
            return mInstance
        }
    }

    private val writableDatabase: SQLiteDatabase?
        get() {
            if (mOpenCounter.incrementAndGet() == 1) {
                mDataBase = mBaseDbHelper.writableDatabase
            }
            return mDataBase
        }

    init {
        mBaseDbHelper = BaseDbHelper(context)
    }

    private fun closeDataBase() {
        if (mOpenCounter.decrementAndGet() == 0) {
            if (mDataBase != null) {
                mDataBase!!.close()
            }
        }
    }

    /**
     * 查询指定用户
     *
     * @param userId
     * @return
     */
    fun queryUserInfo(userId: String): UserInfo? {
        //如果Realm关闭,所有查询得到的RealmObject都不能使用了
        val db = writableDatabase
        var result: UserInfo? = null
        try {
            val selection = UserTable.USER_ID + "=?"
            val selectionArgs = arrayOf(userId)
            var cursor: Cursor? = null
            try {
                cursor = db!!.query(UserTable.TABLE_NAME, null, if (TextUtils.isEmpty(userId)) null else selection,
                        if (TextUtils.isEmpty(userId)) null else selectionArgs, null, null, null)
                if (cursor != null) {
                    if (cursor.moveToFirst()) {
                        result = UserInfo()
                        result.parseCursor(cursor)
                    }
                }
            } catch (e: Exception) {
                Log.e(TAG, "[queryUserInfo] error = " + e.message)
            } finally {
                cursor?.close()
            }
        } finally {
            closeDataBase()
        }
        return result
    }

    /**
     * 查询指定用户
     *
     * @return
     */
    fun queryUserInfo(projections: Array<String>, where: String, selectionArgs: Array<String>, sortOrder: String): UserInfo? {
        val db = writableDatabase
        var result: UserInfo? = null
        try {
            var cursor: Cursor? = null
            try {
                cursor = db!!.query(UserTable.TABLE_NAME, projections, where, selectionArgs, null, null, sortOrder)
                if (cursor != null) {
                    if (cursor.moveToFirst()) {
                        result = UserInfo()
                        result.parseCursor(cursor)
                    }
                }
            } catch (e: Exception) {
            } finally {
                cursor?.close()
            }
        } catch (e: Exception) {
            Log.e(TAG, "[queryUserInfo] error = " + e.message)
        } finally {
            closeDataBase()
        }
        return result
    }

    /**
     * 用户信息写入数据库
     *
     * @param userInfo
     */
    fun insertOrUpdate(userInfo: UserInfo): Boolean {
        val db = writableDatabase
        val cursor = db!!.query(
                UserTable.TABLE_NAME,
                arrayOf(UserTable.USER_ID),
                UserTable.USER_ID + " = ?",
                arrayOf(userInfo.userId), null, null, null)
        var result: Long = 0
        try {
            val values = userInfo.contentValues
            if (cursor != null && cursor.count > 0) {
                //更新操作
                cursor.moveToFirst()
                val userId = cursor.getString(cursor.getColumnIndex(UserTable.USER_ID))
                val newId = userInfo.userId
                if (!TextUtils.isEmpty(newId) && newId != userId) {//容错,数据库只有一个用户信息
                    result = db.update(UserTable.TABLE_NAME, values, UserTable.USER_ID + " = ?", arrayOf(userId)).toLong()
                } else {
                    result = db.update(UserTable.TABLE_NAME, values, UserTable.USER_ID + " = ?", arrayOf(userInfo.userId)).toLong()
                }
            } else {
                //插入操作
                result = db.insert(UserTable.TABLE_NAME, null, values)
            }
        } catch (e: Exception) {
            Log.e(TAG, "[insertOrUpdate] error = " + e.message)
        } finally {
            cursor?.close()
            closeDataBase()
        }
        return result > 0
    }

    /**
     * 删除数据库全部数据
     */
    fun deleteAllDatas() {
        val db = writableDatabase
        try {
            db!!.delete(UserTable.TABLE_NAME, null, null)
        } catch (e: Exception) {
            Log.e(TAG, "[deleteAllDatas] error = " + e.message)
        } finally {
            closeDataBase()
        }
    }
}

原文:大专栏  Kotlin 封装 DB 操作举例

原文地址:https://www.cnblogs.com/petewell/p/11584615.html

时间: 2024-11-06 07:29:50

Kotlin 封装 DB 操作举例的相关文章

selenium之封装登陆操作

# selenium 封装登录操作举例 import os, time # from selenium import webdriver class LoginPage(): '''登录模块''' def __init__(self, path=''): '''初始化加载驱动''' if path: chrome_path = path else: chrome_path = "C:\\Users\\nriet\AppData\Local\Google\Chrome\Application\ch

封装JDBC操作数据库的方法

自己动手封装java操作数据库的方法: 一:目录结构 二:所需依赖的第三方jar包 这里只需引入mysql-connector-java-5.1.8-bin.jar,mysql数据库驱动jar包 三:代码 1:和数据库进行交互,首先是数据源,获取连接,代码如下: 1 /** 2 * 3 */ 4 package com.hlcui.datasource; 5 6 import java.sql.Connection; 7 import java.sql.DriverManager; 8 impo

selenium之登陆操作举例

安装selenium: python -m pip install selenium-3.4.3-py2.py3-none-any.whl 下载对应浏览器版本的驱动,且在环境变量PATH中指定驱动程序的存放路径,否则需要指定驱动文件路径. 代码举例: # selenium登录操作举例 import os, time from selenium import webdriver # 指定浏览器安装位置 chrome_path = "C:\\Users\\nriet\AppData\Local\Go

Windows Server 2012 R2 WSUS-12:经典的排错操作举例

本文主要讨论两类错误,一个是在实际部署中,由于错误的配置步骤导致的更新不正常的报错,另外一种就是WSUS部署完成后,在后期运维过程中出现的错误,一般错误主要集中的后期运维时期,可能会出现各种各样的客户端无法更新的报错. (一)部署过程中,错误配置导致客户端无法更新 客户端无法联系WSUS服务器进行补丁更新,通过查看客户机本地的windows update的log文件,发现文件中有下面的错误,如图. 其实上面的这个报错是典型的部署粗心的错误,在前面的文章中我已经多次提到过,在WSUS 3.0时代,

JS封装cookie操作函数实例(设置、读取、删除)

本文实例讲述了JS封装cookie操作函数.分享给大家供大家参考,具体如下: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 /*设置cookie*/ function setCookie(name, value, iDay) {   var oDate=new Date();   oDate.setDate(oDate.getDate()+iDay);   document.cook

ceilometer alarm 创建过程中的DB操作及优化

创建一个ceilometer alarm需要4次DB操作: api/controllers/v2/alarms.py 1. is_over_quota 每一次都需要查询该user/project的所有alarms 2. 判断alarm name是否已经存在于DB中,也需要查询该user/project的所有alarms        # make sure alarms are unique by name per project.        alarms = list(conn.get_a

PHP+MySQL:测试连接+基本DB操作

PHP使用MySQL,从连接.创建.到结果显示 1 <?php 2 //连接MySQL测试 3 $db = mysql_connect("localhost","root","wenwen"); 4 if (!$db) 5 { 6 die('Could not connect: ' . mysql_error()); 7 } 8 else 9 { 10 echo "connect success!"; 11 } 12 1

Kotlin 控制台交互式操作

kotlin 可以使用和控制台进行交互式操作. 还是蛮有意思. 使用Kotlin的交互式操作首先必须要正确的安装JDK和配置JDK的环境. 可以参考这篇文长 安装完成之后就要下载一个Kotlin的交互式操作的配置文件. GitHub:https://github.com/JetBrains/kotlin/releases/tag/v1.1.4-3 下载这个kotlin-compiler文件就可以了. 我们解压好文件. 之后在环境变量里面进行配置就可以了. 之后在在控制台 输入kotlinc 然后

适用于yii1.1的thinkphp化的db操作类

前段时间的一个项目是要对一个用yii1.1写的商城做修改,不怎么好写,不过比面向过程的ecshop好得多,之前刚开始改ecshop还真是头大 yii1.1其中数据库操作花了我不少时间去找各种例子进行测试,出于日后可能还要改的原因,我将数据库的一些操作改成了thinkphp的形式,代码如下 <?php /**gcud数据库操作 * @version 20191231 */ class gcudDb { private $TableName; private $Conditions; private