使用Room在Android應用中操作SQLite數據庫有以下幾個步驟:
implementation "androidx.room:room-runtime:2.x.x"
annotationProcessor "androidx.room:room-compiler:2.x.x"
@Entity(tableName = "users")
public class User {
@PrimaryKey
public int id;
public String name;
public int age;
}
@Dao
public interface UserDao {
@Query("SELECT * FROM users")
List<User> getAllUsers();
@Insert
void insertUser(User user);
@Delete
void deleteUser(User user);
}
@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
AppDatabase db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "database-name").build();
List<User> users = db.userDao().getAllUsers();
User user = new User();
user.id = 1;
user.name = "Alice";
user.age = 25;
db.userDao().insertUser(user);
這樣就可以在Android應用中使用Room對SQLite數據庫進行操作。 Room提供了一種更簡單和類型安全的方式來操作數據庫,避免了使用原始SQL語句的繁瑣和不安全。