android----Room数据库的简单操作(1)

  android数据库的操作和WEB类是,都是增删改查,但是android数据库操作的代码远比WEB的代码要少,而且简单不用写。如果有不懂请看代码注释

  1、用entity、dao、database创建数据库

  entity:是一个实体类

  dao:是一个接口(interface),用来对数据库经常操作

    database:继承RoomDatabase,数据库。

  代码:看代码注释

  entity:

package com.example.roomtest;

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

@Entity // 实体类
public class Word {
    @PrimaryKey(autoGenerate = true) // 将id设置为主键,并且自增
    private int id;
    @ColumnInfo(name = "English")   // 设置每列的名称
    private String English_word;
    @ColumnInfo(name = "Chinese")
    private String Chinese_meaning;
    // 主键不用构造函数
    public  Word(){}
    public Word(String english_word, String chinese_meaning) {
        English_word = english_word;
        Chinese_meaning = chinese_meaning;
    }
    public void setId(int id){
        this.id = id;
    }
    public int getId() {
        return id;
    }
    public String getEnglish_word() {
        return English_word;
    }

    public void setEnglish_word(String english_word) {
        English_word = english_word;
    }

    public String getChinese_meaning() {
        return Chinese_meaning;
    }

    public void setChinese_meaning(String chinese_meaning) {
        Chinese_meaning = chinese_meaning;
    }
}

 

 

 

  Dao:

package com.example.roomtest;

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    // 访问数据库操作的接口 Database access object
public interface WordDao {
    //我们所有对数据库的操作都在Dao里声明
    @Insert   // 这些修饰词会在编译时候生成代码
    void insertWords(Word... words);   // 如果是一个参数就写 Word word,多个参数就这样写
    @Update
    void updataWords(Word... words);
    @Delete
    void deleteWords(Word... words);
    @Query("DELETE  FROM WORD")
    void deleteAllWords();
    @Query("SELECT * FROM WORD ORDER BY ID DESC")  // 获取所有的WORD,并且按照id降序排序
    List<Word> getAllWords();
}

 

  

    Database:

package com.example.roomtest;

import androidx.room.Database;
import androidx.room.RoomDatabase;
/*
    这里有个参数,第一个参数entities是一个集合,因为只有一个实体类,如果有多个可以逗号隔开
    第二个参数是version(版本):每一次数据库的结构发生改变,版本都得改变
    第三个参数是生成数据库表:这里先选择false
 */
@Database(entities = {Word.class},version = 1,exportSchema = false)
public abstract class WordDatabase extends RoomDatabase {
    public abstract  WordDao  getWordDao();
}

    Activity:

    

package com.example.roomtest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.room.Room;
import androidx.room.RoomDatabase;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.w3c.dom.Text;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    WordDatabase wordDatabase;
    WordDao wordDao;
    TextView textView;
    Button buttonInsert,buttonDelete,buttonUpdata,buttonwClear;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        wordDatabase = Room.databaseBuilder(this, WordDatabase.class,"word_database")
                .allowMainThreadQueries().build(); // 强制让它在主线程运行
        wordDao = wordDatabase.getWordDao();
        textView = findViewById(R.id.textView);
        buttonInsert = findViewById(R.id.button_insert);
        buttonDelete= findViewById(R.id.button_delete);
        buttonUpdata = findViewById(R.id.button_updata);
        buttonwClear = findViewById(R.id.button_clear);
        // 插入
        buttonInsert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Word word1 = new Word("Hello", "你好");
                Word word2 = new Word("World", "世界");
                wordDao.insertWords(word1,word2);
                updataView();
            }
        });
        // 清空
        buttonwClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                wordDao.deleteAllWords();
                updataView();
            }
        });
        // 修改
        buttonUpdata.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Word word = new Word("Thanks","谢谢");
                word.setId(29);
                wordDao.updataWords(word);
                updataView();
            }
        });
        // 删除
        buttonDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Word word = new Word("aa", "bb");
                word.setId(30);
                wordDao.deleteWords(word);
                updataView();
            }
        });

    }

    // 更新界面
    void updataView(){
        List<Word> list = wordDao.getAllWords();
        StringBuilder text = new StringBuilder();
        for(int i = 0;i<list.size();i++){
            Word word = list.get(i);
            text.append(word.getId()).append("、").append(word.getEnglish_word()).append(":").append(word.getChinese_meaning()).append('\n');
        }
        textView.setText(text);
    }

}

  

    运行结果:点击可以执行相应功能。这是最基础的功能。

  android----Room数据库的简单操作(1)

 

 

 

上一篇:Android开发 SingleLiveEvent解决LiveData或者MutableLiveData多次回调的问题


下一篇:[android]com.android.support:appcompat-v7:XXX 包导入无法Build