Android使用SQLite数据库实现基本的增删改查
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
class DatabaseHelper(context: Context) : SQLiteOpenHelper(context, "mydatabase.db", null, 1) {
override fun onCreate(db: SQLiteDatabase) {
val createTableStatement = "CREATE TABLE IF NOT EXISTS user_table " +
"(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)
val success = db.insert("user_table", null, contentValues)
db.close()
}
fun deleteData(id: Int) {
val db = this.writableDatabase
db.delete("user_table", "id = ?", arrayOf(id.toString()))
db.close()
}
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("user_table", contentValues, "id = ?", arrayOf(id.toString()))
db.close()
}
fun retrieveData(): Cursor {
val db = this.readableDatabase
return db.query("user_table", null, null, null, null, null, null)
}
}
这段代码展示了如何在Android中使用SQLiteOpenHelper创建和管理一个简单的数据库,并实现了基本的增删改查操作。使用时,你需要创建DatabaseHelper的实例,并调用相应的方法来执行数据库操作。
评论已关闭