Android Room 的使用(使用room实现增删改查)

封装了SQlite

第一步:创建数据库表类

package com.example.room;

import androidx.room.ColumnInfo;
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 int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

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

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

    public Student() {
    }

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

第二步:创建对数据库增删改查的接口

package com.example.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 insertStudent(Student... students);
//有条件删除
@Delete
    void deleteStudent(Student... students);
@Update
    void updateStudent(Student... students);
//查询所有
@Query("select * from student")
    List<Student>  getAllStudent();
//有条件查询没有成功
@Query("select * from student where id = :id")
    List<Student> getStudentById(int id);
//删除所有
@Query("DELETE FROM Student")
   void deleteAllStudent();
}

第三步:创建数据库操作类,使用他获取到Dao接口中的方法对数据库进行操作,(单例模式)

package com.example.room;


import android.content.Context;

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

//将数据库与Dao相连接
@Database(entities = {Student.class}, version = 1, exportSchema = false)
public abstract class MyDatabase extends RoomDatabase {
    //数据库的名字
    private static final String DATABASE_NAME = "my_db.db";
    private static MyDatabase mInstance;

    //将MyDataBase设置为单例模式
    public static synchronized MyDatabase getInstance(Context context) {
        if (mInstance == null) {
            mInstance = Room.databaseBuilder(context.getApplicationContext(), MyDatabase.class, DATABASE_NAME)
                    //  .allowMainThreadQueries()//运行在主线成中进行耗时任务
                    .build();
        }
        return mInstance;
    }

//只需声明一下即可
    public abstract StudentDao getStudentDao();

}

第四步:在主业面调用

package com.example.room;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;

import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    StudentDao studentDao;
    RecyclerView lv;
    List<Student> list;
    Button btInsert,btDelAll,btSelAll,btUpdate,btSelOne,btDelOne;
    Student s1,s2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initview();
        initevent();
        s1 = new Student(1,"jack" ,21);
        s2 = new Student(2,"AA",66);
        list = new ArrayList<>();
        //获取到数据库操作类
        MyDatabase database = MyDatabase.getInstance(this);
        studentDao = database.getStudentDao();
        //设置列表显示
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        lv.setLayoutManager(layoutManager);

    }

    //监听方法
    private void initevent() {
        btInsert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                insert(s1,s2);
            }
        });
        btSelAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                select();

                lv.setAdapter(new MyRecycleAdapter(list,MainActivity.this));
            }
        });
        btDelAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                delall();
            }
        });
        btUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Student sUpdate = new Student("liyuanba",99);
                sUpdate.setId(1);
                update(sUpdate);
            }
        });
        btDelOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                delone(s1);
            }
        });
        btSelOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
    }

    //初始化方法
    private void initview() {
        btInsert = findViewById(R.id.btInsert);
        btSelAll = findViewById(R.id.btSelAll);
        btDelOne = findViewById(R.id.btdelAll);
        btUpdate = findViewById(R.id.btUpdate);
        btDelAll = findViewById(R.id.btDelOne);
        btSelOne = findViewById(R.id.btSelOne);
        lv = findViewById(R.id.lv);
    }


    //添加
    public void insert(Student...students) {

        new InsertStudentTask(studentDao).execute(students);
    }

    class InsertStudentTask extends AsyncTask<Student ,Void, Void>{
      private StudentDao studentDao;

        public InsertStudentTask(StudentDao studentDao) {
            this.studentDao = studentDao;
        }

        @Override
        protected Void doInBackground(Student... students) {
        studentDao.insertStudent(students);
            return null;
        }
    }



    //查询所有
    public void select() {

    new GetAlltStudentTask(studentDao).execute();
    }

    class GetAlltStudentTask extends AsyncTask<Void ,Void, Void>{
        private StudentDao studentDao;

        public GetAlltStudentTask(StudentDao studentDao) {
            this.studentDao = studentDao;
        }
        @Override
        protected Void doInBackground(Void...voids) {
        list = studentDao.getAllStudent();
        return null;
        }
    }

    //有条件删除
    public void delone(Student...students){

        new DelStudentTesk(studentDao).execute(students);
    }

    class DelStudentTesk extends AsyncTask<Student,Void,Void>{
        private StudentDao studentDao;

        public DelStudentTesk(StudentDao studentDao) {
            this.studentDao = studentDao;
        }

        @Override
        protected Void doInBackground(Student... students) {
            studentDao.deleteStudent(students);
            return null;
        }
    }

    //修改
    public void update(Student...students){

        new UpdateStudentTesk(studentDao).execute(students);
    }

    class UpdateStudentTesk extends AsyncTask<Student,Void,Void>{
        private StudentDao studentDao;

        public UpdateStudentTesk(StudentDao studentDao) {
            this.studentDao = studentDao;
        }

        @Override
        protected Void doInBackground(Student... students) {
            studentDao.updateStudent(students);
            return null;
        }
    }

    //删除所有
    public void delall() {

        new GetAlltStudentTask(studentDao).execute();
    }

    class DelAlltStudentTask extends AsyncTask<Void ,Void, Void>{
        private StudentDao studentDao;

        public DelAlltStudentTask(StudentDao studentDao) {
            this.studentDao = studentDao;
        }
        @Override
        protected Void doInBackground(Void...voids) {
              studentDao.deleteAllStudent();
            return null;
        }
    }


}

主页面布局

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <Button
            android:id="@+id/btInsert"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="3dp"
            android:layout_marginTop="28dp"
            android:layout_marginEnd="7dp"
            android:layout_marginBottom="31dp"
            android:text="增加"
            app:layout_constraintBottom_toTopOf="@+id/btUpdate"
            app:layout_constraintEnd_toStartOf="@+id/btdelAll"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <Button
            android:id="@+id/btdelAll"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="28dp"
            android:text="删除"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/btInsert"
            app:layout_constraintTop_toTopOf="parent" />

        <Button
            android:id="@+id/btUpdate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="4dp"
            android:layout_marginEnd="18dp"
            android:layout_marginBottom="72dp"
            android:text="更改"
            app:layout_constraintBottom_toTopOf="@+id/lv"
            app:layout_constraintEnd_toStartOf="@+id/btSelAll"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/btInsert" />

        <Button
            android:id="@+id/btSelAll"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="31dp"
            android:text="查询"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/btUpdate"
            app:layout_constraintTop_toBottomOf="@+id/btdelAll" />



        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/lv"
            android:layout_width="400dp"
            android:layout_height="0dp"
            android:layout_marginStart="1dp"
            android:layout_marginBottom="1dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/btUpdate" />

        <Button
            android:id="@+id/btDelOne"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="81dp"
            android:layout_marginTop="11dp"
            android:layout_marginEnd="236dp"
            android:layout_marginBottom="13dp"
            android:text="删除所有"
            app:layout_constraintBottom_toTopOf="@+id/lv"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/btUpdate" />

        <Button
            android:id="@+id/btSelOne"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="84dp"
            android:layout_marginTop="11dp"
            android:layout_marginEnd="58dp"
            android:layout_marginBottom="13dp"
            android:text="有条件查询"
            app:layout_constraintBottom_toTopOf="@+id/lv"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/btDelOne"
            app:layout_constraintTop_toBottomOf="@+id/btSelAll" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

依赖(java的依赖)

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

Android开发中,增删改查是常见的数据库操作。首先,我们需要创建一个数据库帮助类来定义数据库的结构和版本号,然后在该类中实现数据库的创建和升级操作。接着,我们可以创建一个数据模型类来定义数据库中的表和字段。接下来,我们通过SQLiteDatabase类来实现增删改查操作。 增加数据:我们可以通过ContentValues类来存储要插入的数据,然后调用SQLiteDatabase的insert()方法将数据插入到数据库中。 删除数据:我们可以使用SQLiteDatabase的delete()方法来删除符合特定条件的数据。我们可以通过提供相应的条件参数来删除特定的数据行。 更新数据:要更新数据,我们可以使用SQLiteDatabase的update()方法来执行更新操作。我们需要提供要更新的数据和更新条件作为参数。 查询数据:最后,我们可以使用SQLiteDatabase的query()方法来执行查询操作。我们可以指定要查询的表、列、条件、排序等参数来获取我们需要的数据。 除了使用原生的SQLiteDatabase类进行增删改查操作,我们还可以使用更高级的框架比如Room来简化数据库操作。Room提供了一个更加方便的方式来定义数据库和操作数据,使得增删改查变得更加简单。 总之,在Android开发中,数据库操作是一个非常重要的部分。通过以上方法,我们可以实现对数据的增删改查操作,并且可以根据实际需求选择合适的方法和框架来进行操作。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值