Skip to content

Instantly share code, notes, and snippets.

@hikaMaeng
Created January 20, 2025 11:12
Show Gist options
  • Save hikaMaeng/b5aee7bc623d87bcdb787a5bb865ae0c to your computer and use it in GitHub Desktop.
Save hikaMaeng/b5aee7bc623d87bcdb787a5bb865ae0c to your computer and use it in GitHub Desktop.
package kore.sqlite
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteStatement
import java.io.File
class SQLite(
private val context: Context,
private val fileName:String? = null
){
private var _db: SQLiteDatabase? = null
private val db:SQLiteDatabase get() = _db ?: run{
val dbFile = File(context.getDatabasePath(fileName), "$fileName.sqlite")
dbFile.parentFile?.mkdirs()
SQLiteDatabase.openOrCreateDatabase(dbFile, null).also{_db = it}
}
private fun fillResult(cursor: Cursor, container: ArrayList<Map<String, Any?>>) {
val colCount = cursor.columnCount
val colNames = cursor.columnNames
while (cursor.moveToNext()) {
val row = mutableMapOf<String, Any?>()
for (i in 0 until colCount) {
row[colNames[i]] = when (cursor.getType(i)) {
Cursor.FIELD_TYPE_NULL -> null
Cursor.FIELD_TYPE_INTEGER -> cursor.getLong(i)
Cursor.FIELD_TYPE_FLOAT -> cursor.getDouble(i)
Cursor.FIELD_TYPE_STRING -> cursor.getString(i)
Cursor.FIELD_TYPE_BLOB -> cursor.getBlob(i)
else -> null
}
}
container.add(row)
}
}
fun close() {
if(db.isOpen) db.close()
}
fun exec(sql: String):Boolean
= try{
db.execSQL(sql)
true
}catch(_:Exception){
false
}
fun select(sql:String):ArrayList<Map<String, Any?>>?
= try{
db.rawQuery(sql, null).use {cursor->
val result = arrayListOf<Map<String, Any?>>()
fillResult(cursor, result)
result
}
}catch(_:Exception){
null
}
fun execPrepared(sql: String, block:(SQLiteStatement)->Unit):Int
= try{
db.compileStatement(sql).use{
block(it)
it.executeUpdateDelete()
}
}catch(_:Exception){
-1
}
fun selectPrepared(sql: String, vararg args: String): ArrayList<Map<String, Any?>> {
val result = arrayListOf<Map<String, Any?>>()
db.rawQuery(sql, args).use { cursor ->
fillResult(cursor, result)
return result
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment