可以通过以下步骤实现:
以下是一个示例代码:
// 创建数据库和表
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "UserDB";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "User";
private static final String COLUMN_USERNAME = "username";
private static final String COLUMN_PASSWORD = "password";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableQuery = "CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_USERNAME + " TEXT PRIMARY KEY, " +
COLUMN_PASSWORD + " TEXT)";
db.execSQL(createTableQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 升级数据库时的操作
}
}
// 插入数据
public class UserDAO {
private DBHelper dbHelper;
public UserDAO(Context context) {
dbHelper = new DBHelper(context);
}
public void insertUser(String username, String password) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DBHelper.COLUMN_USERNAME, username);
values.put(DBHelper.COLUMN_PASSWORD, password);
db.insert(DBHelper.TABLE_NAME, null, values);
db.close();
}
}
// 验证用户名和密码
public class UserDAO {
private DBHelper dbHelper;
public UserDAO(Context context) {
dbHelper = new DBHelper(context);
}
public boolean validateUser(String username, String password) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
String[] columns = {DBHelper.COLUMN_USERNAME, DBHelper.COLUMN_PASSWORD};
String selection = DBHelper.COLUMN_USERNAME + " = ? AND " + DBHelper.COLUMN_PASSWORD + " = ?";
String[] selectionArgs = {username, password};
Cursor cursor = db.query(DBHelper.TABLE_NAME, columns, selection, selectionArgs, null, null, null);
boolean isValid = cursor.moveToFirst();
cursor.close();
db.close();
return isValid;
}
}
这个程序使用了SQLite数据库来保存用户名和密码。在创建数据库和表时,使用了SQLiteOpenHelper类。在插入数据时,使用了SQLiteDatabase的insert方法。在验证用户名和密码时,使用了SQLiteDatabase的query方法。
领取专属 10元无门槛券
手把手带您无忧上云