SQLite3

246 阅读1分钟

一、创建数据库

【1】 继承SQLiteOpenHelper进行创建数据库,实现onCreate和onUpgrade方法

【2】 SQLiteOpenHelper中有两个重要的方法,getReadableDatabase和getWritableDatabase,这两个方法都是可以打开数据库的,如果数据库不存在则会创建一个数据库,这两个方法的区别在于,如果数据库不可写入的时候,例如:磁盘已满,getReadableDatabase返回的对象将以只读的方式打开数据库,如果使用getWritableDatabase时,则会抛异常

【3】 sqlite的数据类型:

①	整型:integer
②	浮点型:real
③	文本类型:text
④	二进制类型:blob

【4】 创建数据库

fun createDataSource(view: View) {
    val dataSourceHelper = DataSourceHelper(this)
    dataSourceHelper.readableDatabase
}

【5】 在data/data/应用包名/databases下生成了db文件,可以使用sqlite3命令进行查看

sqlite3 数据库名称  ->进入数据库
.table	列出该数据库下的所有表
.schema	显示出建表的语句
.exit/.quit	退出

二、数据库升级

【1】 向已存在的数据库中添加表,需要在onUpgrade方法中,先删除已存在的表,再调用onCreate进行创建表,注意版本号要比原来的大

class DataSourceHelper(private val context: Context) : SQLiteOpenHelper(context, "BookStore.db", null, 3) {
override fun onCreate(db: SQLiteDatabase?) {
    val tableSql =
            "create table book(id integer primary key autoincrement,author text,price real,pages integer,name text)"
    db?.execSQL(tableSql)
    val categorySql = "create table category(id integer primary key autoincrement,category_name text)"
    db?.execSQL(categorySql)
    Toast.makeText(context, "数据库创建完成", Toast.LENGTH_SHORT).show()
}

override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
    db?.execSQL("drop table if exists book")
    db?.execSQL("drop table if exists category")
    onCreate(db)
}

}

三、事务控制

【1】 原子操作时需要使用事务控制

【2】 SQLiteDatabase中提供了beginTransaction,setTransactionSuccessful,endTransaction等事务操作的方法

fun bookTransaction(){
    val database = databaseHelper.readableDatabase
    // 开启事务
    database.beginTransaction()
    bookDelete()
    bookInsert()
    database.setTransactionSuccessful()
    database.endTransaction()
}