今天记录下对 使用 room 操作数据库的知识
1.添加依赖项(好像需要添加新的版本)
implementation 'android.arch.persistence.room:runtime:1.1.0-beta2'
annotationProcessor 'android.arch.persistence.room:compiler:1.1.0-beta2'
implementation 'android.arch.persistence.room:rxjava2:1.1.0-beta2'
2.添加数据库对应的 表的属性
@Entity
public class User {
@PrimaryKey
public int uid;
public String name;
public String password;
}
3.添加操作数据的函数
@Dao
public interface UserDao {
@Query("select * from User")
List<User> getAll();
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertUser(User user);
@Delete
void deleteUser(User user);
}
4.添加数据库
@Database(entities = {User.class},version = 2)
public abstract class UserDatabase extends RoomDatabase {
public abstract UserDao getUserDao();
}
5.得到 table 对象 和 对应的操作
public class MainActivity extends AppCompatActivity {
private String TAG = "MainActivity";
private UserDatabase userDatabase = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseOperation();
}
private void databaseOperation() {
//得到数据表对象
userDatabase = Room.databaseBuilder(this, UserDatabase.class, "user.db")
.allowMainThreadQueries()
.fallbackToDestructiveMigration().build();
UserDao mUserDao = userDatabase.getUserDao();
writeDatabase(mUserDao, 1,"zhang", "123456");
writeDatabase(mUserDao, 2,"li", "123");
readDatabase(mUserDao);
}
private void readDatabase(UserDao dao) {
List<User> users = dao.getAll();
for (User u : users) {
Log.e(TAG, "get user:" + String.valueOf(u.uid) + "name" + u.name );
}
}
private void writeDatabase(UserDao dao, int uid,String name, String password) {
User user = new User();
user.uid = uid;
user.name = name;
user.password = password;
dao.insertUser(user);
}
}
6.遇到的坑
1.Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Landroid/arch/core/executor/AppTool
2.java.lang.IllegalStateException: Room cannot verify the data integrity. Looks like you’ve changed sc
文章地址:
1.https://blog.csdn.net/ygzrsno/article/details/80019755
2.http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2017/0728/8278.html(出现的错误及解决方法)
3.https://blog.csdn.net/zhangphil/article/details/78611632?locationNum=3&fps=1