安卓kotlin使用anko-sqlite数据库,CRUD

一,在项目中使用Anko SQLite

anko-sqlite依赖项添加到您的build.gradle(Module app)

dependencies {
    implementation "org.jetbrains.anko:anko-sqlite:0.10.8"
}

二、访问数据库

Anko提供了一个ManagedSQLiteOpenHelper无缝替换默认类的特殊类。以下是如何使用它:

class MyDatabaseOpenHelper private constructor(ctx: Context) : ManagedSQLiteOpenHelper(ctx, "MyDatabase", null, 1) {
    init {
        instance = this
    }

    companion object {
        private var instance: MyDatabaseOpenHelper? = null

        @Synchronized
        fun getInstance(ctx: Context) = instance ?: MyDatabaseOpenHelper(ctx.applicationContext)
    }

    override fun onCreate(db: SQLiteDatabase) {
        // 在这里创建表
        db.createTable("Customer", true, 
                    "id" to INTEGER + PRIMARY_KEY + UNIQUE,
                    "name" to TEXT,
                    "photo" to BLOB)
    }

    override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
        // 在这里,您可以像往常一样升级表
        db.dropTable("User", true)
    }
}

// Context的访问属性
val Context.database: MyDatabaseOpenHelper
    get() = MyDatabaseOpenHelper.getInstance(this)

三、创建和删除表

使用Anko,您可以轻松创建新表并删除现有表。语法很简单。

database.use {
    createTable("Customer", true, 
        "id" to INTEGER + PRIMARY_KEY + UNIQUE,
        "name" to TEXT,
        "photo" to BLOB)
}

SQLite中,有五种主要类型:NULLINTEGERREALTEXTBLOB。但每列可能有一些像PRIMARY KEYUNIQUE的修饰符。您可以附加此类修饰符,并将它们“添加”到主类型名称。

要删除表,请使用以下dropTable函数:

dropTable("User", true)

四、插入数据

// 其中db是SQLiteDatabase 
// 例如:val db = database.writeableDatabase 
db.insert("User", 
    "id" to 42,
    "name" to "John",
    "email" to "[email protected]"
)

或者在database.use的内部:

database.use {
    insert("User", 
        "id" to 42,
        "name" to "John",
        "email" to "[email protected]"
   )
}

请注意,在上面的示例中database是一个数据库帮助程序实例,并且db是一个SQLiteDatabase对象

函数insertOrThrow()replace()replaceOrThrow()也存在且具有相似的语义。

五、查询数据

Anko提供了一个方便的查询构建器。可以使用db.select(tableName, vararg columns)where db的 SQLiteDatabase实例创建它。

方法 描述
column(String) Add a column to select query
distinct(Boolean) Distinct query
whereArgs(String) Specify raw String where query
whereArgs(String, args) :star: Specify a where query with arguments
whereSimple(String, args) Specify a where query with ? mark arguments
orderBy(String, [ASC/DESC]) Order by this column
groupBy(String) Group by this column
limit(count: Int) Limit query result row count
limit(offset: Int, count: Int) Limit query result row count with an offset
having(String) Specify raw having expression
having(String, args) :star: Specify a having expression with arguments

 

标记:星:的函数以特殊方式解析其参数。它们允许您以任何顺序提供值并支持无缝转义。

db.select("User", "name")
    .whereArgs("(_id > {userId}) and (name = {userName})",
        "userName" to "John",
        "userId" to 42)

猜你喜欢

转载自blog.csdn.net/lojloj/article/details/100143972
今日推荐