Kotlin使⽤SQLite
⾸先确定我们的⽬标,SQLite只是⼀种⼯具,我们需要掌握就是增删改查就可以,我们真正需要动脑的还是项⽬中的业务逻辑。我这篇⽂章写得⽐较适合新⼿,没⽤过SQLite的同学。前期准备⼯作
新建⼀个类MyDataBaseHelper继承⾃SQLiteOpenHelper,代码如下:
class MyDatabaseHelper(var context: Context, name: String, version: Int) : SQLiteOpenHelper(context, name, null, version) { public var createBook=\"create table Book (\" + \"id integer primary key autoincrement,\" + \"author text,\" + \"price real,\" + \"pages integer,\" + \"name text)\"
override fun onCreate(db: SQLiteDatabase?) {// 下⾯这个todo 如果不注释掉的话就会报错。
// TODO(\"not implemented\") //To change body of created functions use File | Settings | File Templates. db?.execSQL(createBook)
Toast.makeText(context,\"Create Successed\ }
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
// TODO(\"not implemented\") //To change body of created functions use File | Settings | File Templates. db?.execSQL(\"drop table if exists Book\") onCreate(db) }}
对数据进⾏操作
操作⽐较简单,下⾯直接看代码:Activity中
class MySQLite : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState)
setContentView(R.layout.activity_my_sqlite)
val dbHelper=MyDatabaseHelper(this,\"BookStore.db\ /**
* 创建表 */
btnCreateDataBase.setOnClickListener { dbHelper.writableDatabase } /**
* 添加数据 */
btnAddData.setOnClickListener { val db=dbHelper.writableDatabase val Values1=ContentValues().apply {// 第⼀条数据
put(\"name\ put(\"author\ put(\"pages\ put(\"price\ }
db.insert(\"Book\
val values2=ContentValues().apply {// 第⼆条数据
put(\"name\ put(\"author\ put(\"pages\ put(\"price\ }
db.insert(\"Book\ }
btnUpdateData.setOnClickListener { val db=dbHelper.writableDatabase val values=ContentValues()
values.put(\"price\
db.update(\"Book\ }
btnDeleteData.setOnClickListener { val db=dbHelper.writableDatabase
db.delete(\"Book\ }
btnQueryData.setOnClickListener { val db=dbHelper.writableDatabase// 查询Book表中所有数据// 这⾥获取到是Cursor对象
val cursor=db.query(\"Book\ if (cursor.moveToFirst()){ do {
val name=cursor.getString(cursor.getColumnIndex(\"name\")) val author=cursor.getString(cursor.getColumnIndex(\"author\")) val pages=cursor.getString(cursor.getColumnIndex(\"pages\")) val price=cursor.getString(cursor.getColumnIndex(\"price\")) Log.d(\"MainActivity\ Log.d(\"MainActivity\ Log.d(\"MainActivity\ Log.d(\"MainActivity\ }while (cursor.moveToNext()) }
cursor.close() } }}
布局⽂件
到此这篇关于Android Kotlin使⽤SQLite案例详解的⽂章就介绍到这了,更多相关Android Kotlin使⽤SQLite内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!
因篇幅问题不能全部显示,请点此查看更多更全内容