简单的轻量级框架,SQL语句不复杂。步骤如下:
添加依赖
dependencies { def room_version="2.3.0" implementation "androidx.room:room-runtime:$room_version" annotationProcessor "androidx.room:room-compiler:$room_version" }
创建实体类
@Entity //实体类注解 public class Data{ @PrimaryKey(autoGenerate = true)//主键自动递增 private int id; @ColumnInfo(name="title")//指定列名,不指定的话列名等于变量名 private String title; @ColumnInfo(name="tt") private String tt; }
创建接口
S Q L查询语句,多个条件用a n d , o r连接
@Dao public interface DataDao { @Insert void insertData(Data data); @Query("delete from data") void deleteAll(); @Query("select * from data") List<Data> findAll(); @Query("delete from data where id =:pos") void deleteById(int pos); @Query("select * from data where tt=:t1 and title=:t2") List<Data> find_by(String t1,String t2); }
创建数据库
单例模式
@Database(entities = {Data.class,Person.class},version = 1,exportSchema = false) public abstract class NDatabase extends RoomDatabase { private static NDatabase INSTANCE; static public NDatabase getDatabase(Context context){ if(INSTANCE==null) { INSTANCE= Room.databaseBuilder(context,NDatabase.class,"n_database") .allowMainThreadQueries().build(); //数据库名 n_database //表名 Data和Person } return INSTANCE; } public abstract DataDao getDataDao(); public abstract PersonDao getPersonDao(); }
获取数据库实例和接口
private NDatabase nDatabase; private DataDao dataDao;
nDatabase=NDatabase.getDatabase(this); dataDao=nDatabase.getDataDao();
增删改查
调用实例后的数据库对象里dao接口的对应方法,比如
List<Data> t=dataDao.findAll();