数据库
首页 > 数据库> > 我在Kotlin中使用Anko时,如何为SQLite表定义一个非空字段?

我在Kotlin中使用Anko时,如何为SQLite表定义一个非空字段?

作者:互联网

我希望在Kotlin中使用Anko时为SQLite表定义一个非null字段.

但是DBRecordTable.Category到TEXT NOT NULL是错误的,我该如何解决?

  implementation "org.jetbrains.anko:anko-sqlite:$anko_version"

  override fun onCreate(db: SQLiteDatabase) {
        db.createTable( DBRecordTable.TableNAME , true,
            DBRecordTable._ID to INTEGER + PRIMARY_KEY+ AUTOINCREMENT,
            DBRecordTable.Category to TEXT NOT NULL,    //It's wrong
            DBRecordTable.Content to TEXT,
            DBRecordTable.IsFavorite to INTEGER  +DEFAULT("0"),
            DBRecordTable.IsProtected to INTEGER  +DEFAULT("0"),
            DBRecordTable.CreatedDate to INTEGER
        )
    }

解决方法:

通过查看sqlTypes.kt,我们可以发现not null约束的定义如下:

val NOT_NULL: SqlTypeModifier = SqlTypeModifierImpl("NOT NULL")

因此,您的代码应为:

override fun onCreate(db: SQLiteDatabase) {
    db.createTable( DBRecordTable.TableNAME , true,
        DBRecordTable._ID to INTEGER + PRIMARY_KEY + AUTOINCREMENT,
        DBRecordTable.Category to TEXT + NOT_NULL,
        DBRecordTable.Content to TEXT,
        DBRecordTable.IsFavorite to INTEGER + DEFAULT("0"),
        DBRecordTable.IsProtected to INTEGER + DEFAULT("0"),
        DBRecordTable.CreatedDate to INTEGER
    )
}

标签:anko,kotlin,android-sqlite,android
来源: https://codeday.me/bug/20191108/2007825.html