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
)
}
}
解决方法:
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
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。