Android移动应用开发之使用room实现数据库的增删改查

Posted Icy Hunter

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android移动应用开发之使用room实现数据库的增删改查相关的知识,希望对你有一定的参考价值。

文章目录

前言

我们直接开门见山,展示一下效果:
数据库的插入和查询:

数据库的修改和查询:

可以看到id为23的数据发生了修改。

删除一条数据:

可以看到id为23的数据被删除了

删除全部数据:

可以看到,数据全都被删除了。
完整代码可运行项目:Android移动应用开发之使用room实现数据库的增删改查

注意:因为设置表的id是主键且自增,因此插入数据id就会持续增加,因为修改和删除都是在MainActivity中手动设置的,是个比较简单的demo,如果需要看到修改和条件删除的效果

修改此处的setId中的参数即可。

核心代码

首先需要添加依赖build.gridle中:

def room_version = "2.2.0-alpha01"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"

定义一张数据表,这里id设置为逐渐且自动增长,就比较方便了。

//一张表
@Entity
public class Student 
    //主键唯一,自动增长
    @PrimaryKey(autoGenerate = true)
    private  int id;

    private String name;

    private int age;
    

然后设置getter和setter的方法,以及带参数的构造方法,就是一个完整的表了:

package demo.demo.room;

import androidx.room.Entity;
import androidx.room.PrimaryKey;

//一张表
@Entity
public class Student 
    //主键唯一,自动增长
    @PrimaryKey(autoGenerate = true)
    private  int id;

    private String name;

    private int age;


    public Student(String name, int age) 
        this.name = name;
        this.age = age;
    

    public int getId() 
        return id;
    

    public String getName() 
        return name;
    

    public int getAge() 
        return age;
    

    public void setId(int id) 
        this.id = id;
    

    public void setName(String name) 
        this.name = name;
    

    public void setAge(int age) 
        this.age = age;
    

    @Override
    public String toString() 
        return "Student" +
                "id=" + id +
                ", name='" + name + '\\'' +
                ", age=" + age +
                '';
    


然后建立一个StudentDatabase抽象类,用于数据库的创建:

package demo.demo.room;

import android.content.Context;

import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;

@Database(entities = Student.class, version = 1, exportSchema = false)
public abstract class StudentDatabase extends RoomDatabase 
    //暴露Dao
    public abstract StudentDao getStudentDao();
    private static StudentDatabase INSTANCE;
    public static synchronized StudentDatabase getInstance(Context context)
        if(INSTANCE == null)
            INSTANCE = Room.databaseBuilder
                    (context.getApplicationContext(),
                    StudentDatabase.class, "student_database")
//                    .allowMainThreadQueries()
                    .build();
        
        return INSTANCE;
    


然后创建一个能对数据库进行增删改查的Dao接口:

package demo.demo.room;

import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;

import java.util.List;

@Dao//对表操作,增删改查
public interface StudentDao 
    @Insert
    void insertStudents(Student...students);

    @Update
    void updateStudents(Student...students);

    //条件删除
    @Delete
    void deleteStudents(Student...students);

    //删除所有
    @Query("DELETE FROM Student")
    void deleteAllStudents();

    @Query("SELECT * FROM Student ORDER BY ID DESC")
    List<Student>getAllStudent();



最后就是编写数据库的引擎,具体对数据库进行操作,发挥实质性作用(采用异步操作):

package demo.demo.room.manager;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import java.util.List;

import demo.demo.room.Student;
import demo.demo.room.StudentDao;
import demo.demo.room.StudentDatabase;

public class DBEngine 
    private StudentDao studentDao;

    public DBEngine(Context context)
        StudentDatabase studentDatabase = StudentDatabase.getInstance(context);
        studentDao = studentDatabase.getStudentDao();
    
    public void insertStudent(Student...students)
        new InsertAsyncTask(studentDao).execute(students);
    

    public void updateStudents(Student...students)
        new UpdateAsyncTask(studentDao).execute(students);
    

    public void deleteStudents(Student...students)
        new DeleteAsyncTask(studentDao).execute(students);
    

    public void deleteAllStudents()
        new DeleteAllAsyncTask(studentDao).execute();
    

    public void queryAllStudents()
        new QueryAllAsyncTask(studentDao).execute();
    

    //异步
    static class UpdateAsyncTask extends AsyncTask<Student, Void, Void>
        private StudentDao dao;
        public UpdateAsyncTask(StudentDao studentDao)
            dao = studentDao;
        
        @Override
        protected Void doInBackground(Student... students) 
            dao.updateStudents(students);
            return null;
        
    

    //条件删除
    static class DeleteAsyncTask extends AsyncTask<Student, Void, Void>
        private StudentDao dao;
        public DeleteAsyncTask(StudentDao studentDao)
            dao = studentDao;
        
        @Override
        protected Void doInBackground(Student... students) 
            dao.deleteStudents(students);
            return null;
        
    

    //全部删除
    static class DeleteAllAsyncTask extends AsyncTask<Void, Void, Void>
        private StudentDao dao;
        public DeleteAllAsyncTask(StudentDao studentDao)
            dao = studentDao;
        
        @Override
        protected Void doInBackground(Void... voids) 
            dao.deleteAllStudents();
            return null;
        
    


    static class QueryAllAsyncTask extends AsyncTask<Void, Void, Void>
        private StudentDao dao;
        public QueryAllAsyncTask(StudentDao studentDao)
            dao = studentDao;
        
        @Override
        protected Void doInBackground(Void... students) 
            List<Student> allStudent = dao.getAllStudent();
            //遍历全部查询的结果
            for(Student student : allStudent)
                Log.e("Hunter", student.toString());
            
            return null;
        
    

    static class InsertAsyncTask extends AsyncTask<Student, Void, Void>
        private StudentDao dao;
        public InsertAsyncTask(StudentDao studentDao)
            dao = studentDao;
        
        @Override
        protected Void doInBackground(Student... students) 
            dao.insertStudents(students);
            return null;
        
    


最后MainActivity进行引擎的调用,对数据库进行操作:

package demo.demo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

import demo.demo.room.Student;
import demo.demo.room.manager.DBEngine;

public class MainActivity extends AppCompatActivity 
    private DBEngine dbEngine;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dbEngine = new DBEngine(this);
    

    public void insertAction(View view) 
        Student student1 = new Student("hunter", 10);
        Student student2 = new Student("icy hunter", 10);
        dbEngine.insertStudent(student1, student2);
    

    public void updateAction(View view) 
        Student student = new Student("hunterr", 20);
        //修改下标为23的
        student.setId(23);
        dbEngine.updateStudents(student);
    

    public void deleteAction(View view) 
        Student student = new Student(null, 0);
        student.setId(23);
        dbEngine.deleteStudents(student);
    

    public void queryAction(View view) 
        dbEngine.queryAllStudents();
    

    public void deleteAllAction(View view) 
        dbEngine.deleteAllStudents();
    

上面增删改查的操作和布局中的按钮绑定即可。

运行效果就如开局所示。

以上是关于Android移动应用开发之使用room实现数据库的增删改查的主要内容,如果未能解决你的问题,请参考以下文章

Android开发笔记(一百七十五)利用Room简化数据库操作

Android开发笔记(一百七十五)利用Room简化数据库操作

Android开发笔记(一百七十五)利用Room简化数据库操作

将表移动到新的数据库迁移 Room Android

Android compose wanandroid app之搜索页面实现

android 开发进程 0.37 room数据存储的使用