Android Studio 中使用 SQLite 数据库实现登录和注册
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
class UserDatabaseOpenHelper(context: Context) : SQLiteOpenHelper(context, "UserInfo.db", null, 1) {
override fun onCreate(db: SQLiteDatabase) {
val createTableUser = "CREATE TABLE IF NOT EXISTS User (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"username TEXT, " +
"password TEXT)"
db.execSQL(createTableUser)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
// 这里可以执行数据库升级操作
}
}
class UserDataBaseAdapter(context: Context) {
private val database: SQLiteDatabase
private val dbOpenHelper: UserDatabaseOpenHelper = UserDatabaseOpenHelper(context)
init {
database = dbOpenHelper.writableDatabase
}
fun register(username: String, password: String): Boolean {
val contentValues = ContentValues()
contentValues.put("username", username)
contentValues.put("password", password)
val result = database.insert("User", null, contentValues)
return result != -1L
}
fun login(username: String, password: String): Boolean {
val selectQuery = "SELECT * FROM User WHERE username = '$username' AND password = '$password'"
val cursor = database.rawQuery(selectQuery, null)
return cursor.moveToFirst()
}
}
这段代码定义了一个UserDatabaseOpenHelper类,继承自SQLiteOpenHelper,用于创建和管理SQLite数据库。UserDataBaseAdapter类封装了注册和登录的方法,使用ContentValues存储用户数据,并通过SQLiteDatabase执行数据库操作。注意,在实际应用中,用户密码应该加密存储,以上代码为示例,未包含加密逻辑。
评论已关闭