使用LitePal操作数据库
配置
dependencies {
implementation 'org.litepal.guolindev:core:3.2.2'
}
在main目录下新建文件夹assets,再新建litepal.xml文件
<?xml version="1.0" encoding="utf-8" ?>
<litepal>
<dbname value = "BookStore"></dbname>
<version value = "1"></version>
<list>
</list>
</litepal>
AndroidMainFest的application中添加android:name="org.litepal.LitePalApplication"
创建和升级数据库
创建一个Book类
public class Book extends LitePalSupport{
private int id;
private String author;
private double price;
private int pages;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
将Book类添加到映射模型列表中,在litepal.XML的< list >< /list>中添加
<mapping class="com.example.administrator.sample.Book"></mapping>
< mapping>标签声明我们要配置的映射模型类,一定要使用完整的类名
MainActivity中创建数据库及添加数据
case R.id.main_btn_litepal:
LitePal.getDatabase();
break;
case R.id.main_btn_add:
Book book = new Book();
book.setName("Why ZYL So Cute");
book.setAuthor("AYG");
book.setPages(100);
book.setPrice(99.99);
book.save();
break;
若向表里添加列,直接在Book类添加字段;
若向数据库添加表,直接再新建一个类,并添加到映射模型列表中即可
版本号记得+1
terminal查看数据库
键入adb shell进入到设备控制台
更新数据
case R.id.main_btn_update:
Book book1 = new Book();
book1.setPages(50);
book1.updateAll("name = ? and author = ?","Why ZYL So Cute","AYG");
break;
删除数据
case R.id.main_btn_delete:
LitePal.deleteAll("book","id = ?","2");
break;
查询数据
case R.id.main_btn_query:
List<Book> books = LitePal.findAll(Book.class);
for(Book book2: books){
Log.d("MainActivity","book's name is "+book2.getName());
Log.d("MainActivity","book's author is "+book2.getAuthor());
}
//查询第一条数据
Book firstData = LitePal.findFirst(Book.class);
//查询最后一条数据
Book lastData = LitePal.findLast(Book.class);
Book data = LitePal.select("name","author").find(Book.class);
Book data = LitePal.where("pages > ?","400").find(Book.class);
//排序
Book data = LitePal.order("price desc").find(Book.class);
//指定查询结构的数量
Book data = LitePal.limit(3).find(Book.class);
//查询结果的偏移量,如查询表中的第2条、第3条、第4条数据
Book data = LitePal.limit(3).offset(1).find(Book.class);
List<Book> books = LitePal.select("name","author")
.where("pages > ?","400")
.order("pages")
.limit(10)
.offset(10)
.find(Book.class);