使用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语句的繁琐和不安全。