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) {
// 这里处理数据库升级的逻辑
}
fun insertData(name: String, age: Int) {
val db = this.writableDatabase
val contentValues = ContentValues()
contentValues.put("NAME", name)
contentValues.put("AGE", age)
db.insert("Student", null, contentValues)
db.close()
}
fun readData(): MutableList<Pair<String, Int>> {
val data = mutableListOf<Pair<String, Int>>()
val db = this.readableDatabase
val selectQuery = "SELECT * FROM Student"
val cursor = db.rawQuery(selectQuery, null)
if (cursor.moveToFirst()) {
do {
val name = cursor.getString(cursor.getColumnIndex("NAME"))
val age = cursor.getInt(cursor.getColumnIndex("AGE"))
data.add(Pair(name, age))
} while (cursor.moveToNext())
}
cursor.close()
db.close()
return data
}
}
这段代码定义了一个DatabaseHelper
类,它继承自SQLiteOpenHelper
。在onCreate
方法中创建了一个名为Student
的表,并定义了两个字段:ID
和NAME
以及AGE
。还提供了insertData
和readData
方法,分别用于插入和读取数据。这个类可以被用来管理学生数据,展示了如何在Android中使用SQLite数据库的基本用法。
评论已关闭