如何在Kotin中使用Anko设计SQLite表?

时间:2017-11-14 06:05:16

标签: android sqlite kotlin android-sqlite anko

我在Kotlin中使用Anko设计了一个非常简单的表,表中有一个名为_id的主键,我希望_id由SQLite系统自动传递值。 我已经阅读了一些示例代码,但我不知道哪一个是正确的,方法1,方法2或方法3?

而且,当我插入记录时,我不认为我需要将值传递给_id,但是MSetting和DBSetting的_id属性必须传递值,所以我必须用{{{ 1}} 我不知道Anko如何处理不必要的_id,我很奇怪,当我反复执行MSetting(10L,"My Settings",2000L,"This is description!")时应用程序不会崩溃!

方法1: SettingManage().addSetting(MSetting(10L,"My Settings",2000L,"This is description!"))

方法2: DBSettingTable._ID to INTEGER + PRIMARY_KEY+ UNIQUE,

方法3: DBSettingTable._ID to INTEGER + PRIMARY_KEY+ AUTOINCREMENT,

插入数据

DBSettingTable._ID to INTEGER + PRIMARY_KEY,

设计表

SettingManage().addSetting(MSetting(10L,"My Settings",2000L,"This is description!"))

业务逻辑

class DBSettingHelper(mContext: Context = UIApp.instance) : ManagedSQLiteOpenHelper(
        mContext,
        DB_NAME,
        null,
        DB_VERSION) {

    companion object {
        val DB_NAME = "setting.db"
        val DB_VERSION = 5
        val instance by lazy { DBSettingHelper() }
    }

    override fun onCreate(db: SQLiteDatabase) {
        db.createTable( DBSettingTable.TableNAME , true,
                DBSettingTable._ID to INTEGER + PRIMARY_KEY,
                DBSettingTable.Name to TEXT,
                DBSettingTable.CreatedDate to INTEGER,
                DBSettingTable.Description to TEXT
        )
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        db.dropTable(DBSettingTable.TableNAME, true)
        onCreate(db)
    }

}



class DBSetting(val mMutableMap: MutableMap<String, Any?>) {
    var _id: Long by mMutableMap
    var name: String by mMutableMap
    var createdDate: Long by mMutableMap
    var description: String by mMutableMap

    constructor(_id: Long, name: String, createdDate: Long, description: String)
            : this(HashMap()) {
        this._id = _id
        this.name = name
        this.createdDate = createdDate
        this.description=description
    }
}


object DBSettingTable {
    val TableNAME = "SettingTable"

    val _ID = "_id"
    val Name = "name"
    val CreatedDate = "createdDate"
    val Description="description"
}

0 个答案:

没有答案