Anko SQLite 增删改查

首先配置Anko SQLite

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

创建数据库:

class MyDatabaseOpenHelper(ctx: Context) : ManagedSQLiteOpenHelper(ctx, "MyDatabase", null, 1) {
    companion object {
        private var instance: MyDatabaseOpenHelper? = null

        @Synchronized
        fun getInstance(ctx: Context): MyDatabaseOpenHelper {
            if (instance == null) {
                instance = MyDatabaseOpenHelper(ctx.getApplicationContext())
            }
            return instance!!
        }
    }

    override fun onCreate(db: SQLiteDatabase) {
        // Here you create tables
        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) {
        // Here you can upgrade tables, as usual
        db.dropTable("User", true)
    }
}

// Access property for Context
val Context.database: MyDatabaseOpenHelper
    get() = MyDatabaseOpenHelper.getInstance(getApplicationContext())

数据库操作代码写在

database.use{
//do something
}

创建表格

createTable("Customer", true, 
        "id" to INTEGER + PRIMARY_KEY + UNIQUE,
        "name" to TEXT,
        "photo" to BLOB)

删除表格

dropTable("User", true)

插入数据

insert(DatabaseHelper.Book.TABLE_NAME, DatabaseHelper.Book.COLUMN_ID to 2, DatabaseHelper.Book.COLUMN_TITLE to result.supID, DatabaseHelper.Book.COLUMN_AUTHOR to result.usrID)

查询数据

//查询表格所有数据
select(DatabaseHelper.Book.TABLE_NAME).exec { parseList(classParser())}

//查询数据
select("User", "name")
    .whereArgs("(_id > {userId}) and (name = {userName})",
        "userName" to "John",
        "userId" to 42)

改数据

update(DatabaseHelper.Book.TABLE_NAME,DatabaseHelper.Book.COLUMN_TITLE to result.supID, DatabaseHelper.Book.COLUMN_AUTHOR to result.usrID).whereSimple("id=2").exec()

删数据

delete(DatabaseHelper.Book.TABLE_NAME,"id=2")
源代码: 点击这里




你可能感兴趣的:(android,kotlin)