Android Kotlin SQLite读写操作源码实例

首次发布:2024-11-05 15:52
package com.zhkh.khpec.utility

import android.annotation.SuppressLint
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper

class DatabaseHelper(context: Context?) : SQLiteOpenHelper(context, "data.db", null, 1) {

    override fun onCreate(db: SQLiteDatabase) {
        // 创建表 执行readableDatabase 或writableDatabase 时,如果数据库文件不存在,则执行onCreate
        val createTableSQL = "CREATE TABLE IF NOT EXISTS testTB (" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "name TEXT, " +
                "email TEXT)"
        db.execSQL(createTableSQL)
        println("lqwvje数据DB:启动创建数据库")
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        // 更新数据库 执行readableDatabase 或writableDatabase 时,如果SQLiteOpenHelper参数 version版本高于原来的版本,则执行onUpgrade
        println("lqwvje数据DB:启动更新数据")
        //        val alterTableSQL = "ALTER TABLE user_table ADD COLUMN phone TEXT"
        //        db.execSQL(alterTableSQL)
    }

    fun add() {
        val db = this.writableDatabase
        try {
            val insertSQL = "INSERT INTO testTB (name, email) VALUES (?, ?)"
            val args = arrayOf("罗分明", "123@luofenming.com")
            db.execSQL(insertSQL, args)
            println("lqwvje数据DB:启动写")
        } catch (e: Exception) {
            println("lqwvje数据库写入异常:" + e.message)
        }
        db.close()
    }

    @SuppressLint("Range")
    fun query() {
        val db = this.readableDatabase
        val selectSQL = "SELECT * FROM testTB"
        try {
            val cursor = db.rawQuery(selectSQL, null)
            if (cursor.moveToFirst()) {
                do {
                    val name = cursor.getString(cursor.getColumnIndex("name"))
                    val email = cursor.getString(cursor.getColumnIndex("email"))
                    println("lqwvje数据DBname:" + name)
                    println("lqwvje数据DBemail:" + email)
                    // ... 处理其他字段
                } while (cursor.moveToNext())
            }
            cursor.close()
        } catch (e: Exception) {
            println("lqwvje数据库读取异常:" + e.message)
        }
        db.close()
    }
}

读写调用

val dbHelper = DatabaseHelper(this.context)
dbHelper.add()
dbHelper.query()

本文来自 www.LuoFenMing.com