代码之家  ›  专栏  ›  技术社区  ›  HelloCW

如何使用anko和kotlin获取sqlite表的max-id值?

  •  3
  • HelloCW  · 技术社区  · 6 年前

    DBRecordTable._ID 是一个 INTEGER + PRIMARY_KEY+ AUTOINCREMENT ,我希望得到一个表的最大id值,如果表中没有数据行,则返回零。

    我试着写代码 select(tableName,DBRecordTable._ID).orderBy(DBRecordTable._ID, Desc).limit(1) ,但这不正确,我如何修复它?

    代码

    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
            )
        }   
    
    }
    
    1 回复  |  直到 5 年前
        1
  •  4
  •   aminography    6 年前

    您可以使用 SQL MAX() 功能:

    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
    }