【Android入门到项目实战--4.5】—— SQLite数据库存储实现增删改查
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
class DatabaseHelper(context: Context) : SQLiteOpenHelper(context, "NoteDatabase.db", null, 1) {
override fun onCreate(db: SQLiteDatabase) {
val createTableSQL = "CREATE TABLE NotesTable (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"title TEXT, " +
"description TEXT)"
db.execSQL(createTableSQL)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
val dropTableSQL = "DROP TABLE IF EXISTS NotesTable"
db.execSQL(dropTableSQL)
onCreate(db)
}
fun insertData(title: String, description: String): Long {
val db = this.writableDatabase
val contentValues = ContentValues()
contentValues.put("title", title)
contentValues.put("description", description)
val rowID = db.insert("NotesTable", null, contentValues)
db.close()
return rowID
}
fun deleteData(id: Long) {
val db = this.writableDatabase
db.delete("NotesTable", "id = ?", arrayOf(id.toString()))
db.close()
}
fun updateData(id: Long, title: String, description: String) {
val db = this.writableDatabase
val contentValues = ContentValues()
contentValues.put("title", title)
contentValues.put("description", description)
db.update("NotesTable", contentValues, "id = ?", arrayOf(id.toString()))
db.close()
}
fun getAllData(): Cursor {
val db = this.writableDatabase
return db.query("NotesTable", null, null, null, null, null, null)
}
}
这段代码实现了一个简单的SQLite数据库操作类,包括创建数据库、表、数据的插入、删除、更新以及查询操作。这个类可以作为Android开发中管理数据的一个基础示例。
评论已关闭