본문 바로가기
Projects/It's My Waye

[It's My Waye] 3. DB 기능 구현 - DBHelper

by DevJaewoo 2022. 1. 22.
반응형

DBHelper 작성

이전 글에서 설계한 DB 구조를 바탕으로 Android에서 제공하는 SQLite를 활용한 DBHandler와 Model, Model에 접근할 수 있게 해주는 DAO를 작성했다.

 

 

우선 Android의 DB에 접근하기 위한 DBHandler부터 만들었다.

 

DB 인터페이스 종류로는 Room과 SQLiteOpenHelper가 있는데, Room을 사용하면 편리하겠지만 SQLite를 써서 기본을 다져야겠다는 생각으로 SQLiteOpenHelper를 선택했다. (Room으로 편하게 할걸 그랬다는 후회가...)

 

클래스를 맨 처음 만들었을 때 코드다. 여기에 Insert, Select, Update, Delete 기능을 수행하는 함수를 추가해줬다.

class DBHelper(val context: Context)
    : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {


    override fun onCreate(db: SQLiteDatabase?) {
        Log.i(TAG, "onCreate: ")
    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
        Log.i(TAG, "onUpgrade: ")
    }
}

 

Insert

    fun insert(table: String, values: ContentValues): Int {
        val db = writableDatabase
        val result = db.insert(table, null, values)

        Log.i(TAG, "insert: $values into table $table")
        
        if(result == -1L) {
            throw IOException("Insert to table $table failed.")
        }

        return result.toInt()
    }

Table과 ContentValues를 매개변수로 받아 Insert 해준다.

 

ContentValues는 키값:쌍으로 데이터를 여러개 저장할 수 있는 클래스로, 사용법은 아래와 같다.

kotlin의 apply를 사용하면 데이터를 쉽게 넣을 수 있다.

val values = ContentValues().apply {
    put("키1", "값1");
    put("키2", "값2");
    put("키3", 숫자1);
}

 

Select

    fun selectAll(table: String): Cursor {
        val query = "SELECT * FROM $table"
        return select(query)
    }

    fun select(table: String, whereClause: String): Cursor {
        val query = "SELECT * FROM $table WHERE $whereClause"
        return select(query)
    }

    fun select(query: String): Cursor {
        val db = readableDatabase
        val result = db.rawQuery(query, null)
        //db.close()

        Log.i(TAG, "select: query: $query")

        return result
    }

Table의 모든 데이터를 긁어오는 selectAll 함수, Table과 where절을 넣어 데이터를 선택할 수 있는 select와 그냥 RawQuery를 넣고 데이터를 가져오는 select 함수를 만들었다.

 

Update

    fun update(table: String, values: ContentValues, whereClause: String, whereArg: String) {
        update(table, values, whereClause, arrayOf(whereArg))
    }

    fun update(table: String, values: ContentValues, whereClause: String, whereArgs: Array<String>) {
        val db = writableDatabase
        val result = db.update(table, values, whereClause, whereArgs)

        Log.i(TAG, "update: set $values into table $table, $result rows affected.")
    }

where 하나로 값을 수정하는 update와 다중 where 절로 값을 수정하는 update 함수를 만들었다.

 

Delete

    fun delete(table: String, whereClause: String, whereArg: String) {
        delete(table, whereClause, arrayOf(whereArg))
    }

    fun delete(table: String, whereClause: String, whereArgs: Array<String>) {
        val db = writableDatabase
        val result = db.delete(table, whereClause, whereArgs)

        Log.i(TAG, "delete: from table $table where $whereClause, $result rows affected.")
    }

Update와 마찬가지로 단일, 다중 where로 구분해 함수를 만들었다.

 

완성된 코드는 다음과 같다.

 

DBHelper.kt

class DBHelper(val context: Context)
    : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {


    override fun onCreate(db: SQLiteDatabase?) {
        Log.i(TAG, "onCreate: ")
    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
        Log.i(TAG, "onUpgrade: ")
    }


    fun insert(table: String, values: ContentValues): Int {
        val db = writableDatabase
        val result = db.insert(table, null, values)

        Log.i(TAG, "insert: $values into table $table")
        
        if(result == -1L) {
            throw IOException("Insert to table $table failed.")
        }

        return result.toInt()
    }


    fun selectAll(table: String): Cursor {
        val query = "SELECT * FROM $table"
        return select(query)
    }

    fun select(table: String, whereClause: String): Cursor {
        val query = "SELECT * FROM $table WHERE $whereClause"
        return select(query)
    }

    fun select(query: String): Cursor {
        val db = readableDatabase
        val result = db.rawQuery(query, null)
        //db.close()

        Log.i(TAG, "select: query: $query")

        return result
    }


    fun update(table: String, values: ContentValues, whereClause: String, whereArg: String) {
        update(table, values, whereClause, arrayOf(whereArg))
    }

    fun update(table: String, values: ContentValues, whereClause: String, whereArgs: Array<String>) {
        val db = writableDatabase
        val result = db.update(table, values, whereClause, whereArgs)

        Log.i(TAG, "update: set $values into table $table, $result rows affected.")
    }


    fun delete(table: String, whereClause: String, whereArg: String) {
        delete(table, whereClause, arrayOf(whereArg))
    }

    fun delete(table: String, whereClause: String, whereArgs: Array<String>) {
        val db = writableDatabase
        val result = db.delete(table, whereClause, whereArgs)

        Log.i(TAG, "delete: from table $table where $whereClause, $result rows affected.")
    }
}

 

반응형