【Android Studio】安卓APP期末作品记录之连接sqlite数据库以及简单的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, GENDER TEXT)"
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, gender: String): Long {
val db = this.writableDatabase
val contentValues = ContentValues()
contentValues.put("NAME", name)
contentValues.put("AGE", age)
contentValues.put("GENDER", gender)
val rowID = db.insert("Student", null, contentValues)
db.close()
return rowID
}
fun deleteData(id: Int): Int {
val db = this.writableDatabase
val deleteQuery = "DELETE FROM Student WHERE ID = ?"
val deletedRows = db.delete("Student", "ID = ?", arrayOf(id.toString()))
db.close()
return deletedRows
}
}
这段代码定义了一个DatabaseHelper
类,继承自SQLiteOpenHelper
。在onCreate
方法中创建了一个名为Student
的表,包含ID
、NAME
、AGE
和GENDER
四个字段。onUpgrade
方法用于在数据库版本更新时,删除旧表并重新创建。insertData
方法用于插入学生信息,而deleteData
方法用于删除指定ID的学生信息。这些方法都通过ContentValues进行数据的插入和删除操作。
评论已关闭