android 本地数据库SQLiteDatabase简单使用
可以在启动APP时,初始化本地数据库,检查创建需要的表
1. 初始化库和数据表,可以在
Application文件下 SqlDataUtils.init(this) 使用
class SqlDataUtils { companion object{ var db : SQLiteDatabase? = null //初始化 fun init(context: Context) { //判断库是否存在,不存在就会创建库。reading 是库的名字,可自定义 db = SQLiteDatabase.openOrCreateDatabase(context.filesDir.toString() + "/reading.db3", null) //创建表 if not exists 判断表是否存在,存在就不创建 //primary key autoincrement 主键ID自增 db!!.execSQL("create table if not exists bookshelf(_id integer" + " primary key autoincrement, " + " type integer(2), " + " name varchar(100)," + " b_img varchar(100)," + " addTime date(20))") } } }
2 查询所有内容
var cursor : Cursor = db!!.rawQuery("select * from bookshelf ", null) if(cursor != null){ while(cursor.moveToNext()){ //循环读取下一条数据 var id = cursor.getInt(0).toLong() var type = cursor.getInt(1) var name = cursor.getString(2) } }
3. 根据条件查询指定内容
var name = "名字" var cursor : Cursor = db!!.rawQuery("select type,name from bookshelf where name = '$name'", null) if(cursor != null){ while(cursor.moveToNext()){ //循环读取下一条数据 var r_type = cursor.getInt(0) var r_name = cursor.getString(1) } }
4.查询数据数目
var name = "名字" var cursor : Cursor = db!!.rawQuery("select count(_id) from bookshelf where name = '$name'", null) if(cursor != null){ //光标移动到第一条 cursor.moveToFirst() //获取数据条数 val count = cursor.getInt(0) }
5. 增加数据
val cValue = ContentValues() cValue.put("type",1) cValue.put("name", "小周") db!!.insert("bookmark", null, cValue)
6. 修改数据
db!!.execSQL("UPDATE bookshelf SET type = '${2}' WHERE name = '${name}' '")
7. 删除数据
db!!.delete("bookshelf", "name = ? and type = ?", arrayOf<String>(name,type))