简体   繁体   中英

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
        )
    }   

}

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM