android - 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
)
}
}
解决方案
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
}
推荐阅读
- kotlin - Spring Webflux - 如何以反应友好的方式转换波纹管代码?
- laravel - 处理后工作留在待处理列表中
- return - 如何使用SignTool处理签名EXE文件返回错误:0x80096019?
- docker - 为什么 K8S 不支持 PreStart Hook
- swift - 如何从数组文字正确创建 MTLTexture?
- javascript - 导出变量以便可以从其他模块和全局范围访问的正确方法是什么?
- css - 工具提示被截断
- python - 如何根据输入更改字典的值?
- java - “ArrayList list = new ArrayList()”真的需要“List list = new ArrayList()”吗?
- javascript - 我正在抓取启用了 javascript 且无法抓取单个内容的网站