Android Room是Google为Android应用程序提供的一种持久性库,它简化了与SQLite数据库进行交互的过程。下面是一个使用Android Room的惯用代码示例:
@Entity(tableName = "users")
public class User {
@PrimaryKey
public int id;
@ColumnInfo(name = "username")
public String username;
@ColumnInfo(name = "password")
public String password;
}
@Dao
public interface UserDao {
@Query("SELECT * FROM users")
List getAllUsers();
@Insert
void insertUser(User user);
@Update
void updateUser(User user);
@Delete
void deleteUser(User user);
}
@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
private static AppDatabase instance;
public static synchronized AppDatabase getInstance(Context context) {
if (instance == null) {
instance = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, "app_database")
.build();
}
return instance;
}
}
AppDatabase database = AppDatabase.getInstance(this);
UserDao userDao = database.userDao();
// 插入用户
User user = new User();
user.id = 1;
user.username = "admin";
user.password = "password";
userDao.insertUser(user);
// 查询所有用户
List userList = userDao.getAllUsers();
// 更新用户
user.password = "new_password";
userDao.updateUser(user);
// 删除用户
userDao.deleteUser(user);
通过上述惯用代码,您可以使用Android Room轻松地执行数据库操作。请注意,上述代码示例中的实体类、DAO和数据库类可能需要根据您的具体需求进行调整。此外,还可以使用更高级的查询语句、事务处理等功能来优化和扩展数据库操作。