Android : SQLite 增删改查—简单应用
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
class DatabaseHelper(context: Context) : SQLiteOpenHelper(context, "Student.db", null, 1) {
override fun onCreate(db: SQLiteDatabase) {
val createTableStatement = "CREATE TABLE Student (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, AGE INTEGER)"
db.execSQL(createTableStatement)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
val dropTableStatement = "DROP TABLE IF EXISTS Student"
db.execSQL(dropTableStatement)
onCreate(db)
}
fun insertData(name: String, age: Int): Long {
val db = this.writableDatabase
val contentValues = ContentValues()
contentValues.put("NAME", name)
contentValues.put("AGE", age)
val rowID = db.insert("Student", null, contentValues)
db.close()
return rowID
}
fun displayData(): Cursor {
val db = this.readableDatabase
val data = db.query("Student", null, null, null, null, null, "NAME")
return data
}
fun updateData(id: Int, name: String, age: Int) {
val db = this.writableDatabase
val contentValues = ContentValues()
contentValues.put("NAME", name)
contentValues.put("AGE", age)
db.update("Student", contentValues, "ID = ?", arrayOf(id.toString()))
db.close()
}
fun deleteData(id: Int) {
val db = this.writableDatabase
db.delete("Student", "ID = ?", arrayOf(id.toString()))
db.close()
}
}
这段代码定义了一个名为DatabaseHelper的类,它继承自SQLiteOpenHelper。在这个类中,我们重写了onCreate和onUpgrade方法来创建和更新数据库表。我们还提供了插入、读取、更新和删除数据的函数。这样,开发者可以很容易地在他们的应用程序中使用这个类来管理他们的数据。
评论已关闭