首页 > 解决方案 > 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
        )
    }   

}

标签: androiddatabasesqlitekotlinanko

解决方案


SQL MAX()您可以使用函数找到表内容的最大 id :

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
}

推荐阅读