Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get max _id value of a SQLite table using Anko with Kotlin?

DBRecordTable._ID is a INTEGER + PRIMARY_KEY+ AUTOINCREMENT, I hope to get the max _id value of a table, zero will be return if no data row in the table.

I try to write the code select(tableName,DBRecordTable._ID).orderBy(DBRecordTable._ID, Desc).limit(1), but it's not correct, how can I fix it?

Code

class DBRecordHandler(private val mDBHelper: DBRecordHelper =DBRecordHelper.instance,
                      private val tableName:String =DBRecordTable.TableNAME,
                      private val idField:String=DBRecordTable._ID
                      ) {

 fun getMaxID():Long=mDBHelper.use{
      var myList=select(tableName,DBRecordTable._ID).orderBy(DBRecordTable._ID, Desc).limit(1); 
 }

}



class DBRecordHelper(mContext: Context = UIApp.instance) : ManagedSQLiteOpenHelper(mContext, DB_NAME, null, DB_VERSION) {

    companion object {
        const val DB_NAME = "record.db"
        const val DB_VERSION = 5
        val instance by lazy { DBRecordHelper() }
    }

    override fun onCreate(db: SQLiteDatabase) {
        db.createTable( DBRecordTable.TableNAME , true,
            DBRecordTable._ID to INTEGER + PRIMARY_KEY+ AUTOINCREMENT,           
            DBRecordTable.CreatedDate to INTEGER
        )
    }   

}
like image 619
HelloCW Avatar asked Dec 18 '25 17:12

HelloCW


1 Answers

You can find maximum id of the table contents using SQL MAX() function:

private fun getMaxID(): Int {
    var maxId = 0
    mDBHelper?.use {
        select(DBRecordTable.TableNAME, "MAX(${DBRecordTable._ID}) as maxId").exec {
            moveToNext()
            maxId = getInt(getColumnIndex("maxId"))
        }
    }
    return maxId
}
like image 120
aminography Avatar answered Dec 20 '25 09:12

aminography



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!