当前位置: 首页 > 工具软件 > LBase-Android > 使用案例 >

Android Room 数据库

邬安邦
2023-12-01

删除表 "drop table if exists " + TABLE_NAME
删除数据不删表 "DELETE FROM " + TABLE_NAME

解决Schema export Error:
Schema export directory is not provided to the annotation processor so we cannot export the schema.
You can either provide room.schemaLocation annotation processor argument OR set exportSchema to false.

解决方式一:
给RoomDatabase设置exportSchema注解为false。

@Database(entities = { YourEntity.class }, version = xxx, **exportSchema = false**)
public abstract class AppDatabase extends RoomDatabase {
}

解决方案二:
在项目中gradle中通过 annotationProcessorOptions 注解,为room.schemaLocation指定schemas的子文件夹。

android {
    defaultConfig {
        //指定room.schemaLocation生成的文件路径
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
            }
        }
    }
}

使用步骤:
1、创建实体类,注解规则

@Entity	//数据表名称
public class User {

    @PrimaryKey(autoGenerate = true)	//主键,自增
    private long uid;
    private String name;
    private String address;
    private String phone;
    private Integer age;

    public User(String name, String address, String phone) {
        this.name = name;
        this.address = address;
        this.phone = phone;
    }
  	...
  	
    @Override
    public String toString() {
        return "User{" +
                "uid=" + uid +
                ", name='" + name + '\'' +
                ", address='" + address + '\'' +
                ", phone='" + phone + '\'' +
                ", age=" + age +
                '}';
    }
}

2、创建Dao接口

@Dao
public interface UserDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)  //指明冲突解决方案
    List<Long> insert(User... user);

    @Query("Select * from user")
    Flowable<List<User>> loadUser();

    @Query("delete from user where user.name=:uid")  //根据条件删除
    void delete(String uid);

    @Update(onConflict = OnConflictStrategy.REPLACE)
    void update(User user);

    @Query("delete from user")   //删除全部信息
    void deletAll();

}

3、自定义database,继承roomdatabase

@Database(entities = {User.class,Book.class},version = 3,exportSchema = false)
@TypeConverters({Converters.class})
public abstract class AppDatabase extends RoomDatabase {
    public abstract UserDao userDao();
    public abstract BookDao bookDao();
}

4、Applacation初始化数据库

public class AppApplication extends AppContext {
    private AppDatabase mAppDatabase;

    @Override
    public void onCreate() {
        super.onCreate();

        mAppDatabase = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "android_room_test.db")
                .allowMainThreadQueries()
                .addMigrations(MIGRATION_1_2, MIGRATION_2_3)
                .build();
    }

    public AppDatabase getmAppDatabase() {
        return mAppDatabase;
    }

    static final Migration MIGRATION_2_3 = new Migration(2, 3) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            database.execSQL("create table if not exists 'book'('uid'integer primary key autoincrement,'name' text,'userid' integer,'time' integer)");
        }
    };

    static final Migration MIGRATION_1_2 = new Migration(1, 2) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            database.execSQL("alter table User add column age integer");
        }
    };
}

5、使用

 case R.id.buttonadd:
                int index= (int)(Math.random()*10);
                User user=new User("frank"+index,"address"+index,"176xxxxxxxx"+index);
                mAppDatabase.userDao().insert(user);
                showResult.setText("插入数据:"+user.toString());
                break;
            case R.id.buttondel:
                int index1= (int)(Math.random()*10);
                long index2= (long)(Math.random()*100);
                User user1=new User("frank"+index1,"address"+index1,"176xxxxxxxx"+index1);
                mAppDatabase.userDao().delete(user1.getName());
                showResult.setText("删除数据name:"+user1.getName());
                break;
            case R.id.buttonquery:
                mAppDatabase.userDao().loadUser().subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<List<User>>() {
                            @Override
                            public void accept(List<User> users) throws Exception {
                                if (users!=null){
                                    container.removeAllViews();
                                    for (User user:users){
                                        TextView v=new TextView(TestRoomActivity.this);
                                        v.setText("查询数据:"+user.toString());
                                        container.addView(v);
                                    }
                                }
                            }
                        });
                break;
            case R.id.buttonupdate:
                mAppDatabase.userDao().deletAll();
                break;
 类似资料: