LitePal 数据库使用方法

转发郭神的blog,讲的非常详细,是基于1.6版本,但现在使用的是2.0,有点差别
https://blog.csdn.net/guolin_blog/article/details/38461239
1.首先说一下常用查看数据库adb命令
手机root后 adb shell ->cd data/data/
ls 展示列表 cd进入应用 cd databases进入数据库
sqlite3 demo.db注意选择有.db文件
.table 展示数据库表格
.mode line 列表形式展示数据
pragma table_info(表名); 注意要有分号 查看表格列信息
select * from 表名; 查看添加内容
ctrl+d 退出sqlite

2.配置
(1)在app module dependencies导入

implementation 'org.litepal.android:java:3.0.0'

(2)在src->main->assets 添加litepal.xml。一定要新建文件+写扩展名的形式,不要直接新建xml
在这里插入图片描述

<?xml version="1.0" encoding="utf-8" ?>
<litepal>
    <dbname value="demo" ></dbname>

    <version value="6" ></version>

    <list>
        <mapping class="com.tayh.litepaldemo.News"></mapping>
        <mapping class="com.tayh.litepaldemo.Comment"></mapping>
        <mapping class="com.tayh.litepaldemo.Introduction"></mapping>
        <mapping class="com.tayh.litepaldemo.Category"></mapping>
    </list>
</litepal>

(3)MyApplication 可以直接继承Application ,初始化LitePal就可以了

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        LitePal.initialize(this);
    }
}

(4)Activity 调用数据库语句

 SQLiteDatabase db = Connector.getDatabase();

(5)News 与Introduction 一对一 外键news_id生成在Introduction里,News本身并没有key,这个需要理解一下。News与Category 多对多,生成key在新生成的category_news表中

public class News extends LitePalSupport {
    private int id;
    private String title;
    private String content;
    private Date publishDate;
    private int commentCount;

    private Introduction introduction;//一对一 外键生成在Introduction表里

    private List<Comment> commentList = new ArrayList<Comment>();//一对多

    private List<Category> categoryList = new ArrayList<Category>();//多对多

}
public class Introduction extends LitePalSupport {
    private int id;
    private String guide;
    private String digest;
}
public class Comment extends LitePalSupport {
    private int id;
    private String content;
    private Date publishDate;
    private News news;//多对一

}

public class Category extends LitePalSupport {
    private int id;
    private String name;
    private List<News> newsList = new ArrayList<News>();//多对多
}

在这里插入图片描述
3.增删改查CRUD
(1)存储
* save()方法用于数据储存,返回值为是否存储成功
saveThrows() 存储失败抛出异常
news.getId() 可以获取到储存id

		Comment comment1 = new Comment();
        comment1.setContent("comment1");
        comment1.setPublishDate(new Date());
        comment1.save();
        News news = new News();
        news.setTitle("news1");
        news.setContent("content1");
        news.setPublishDate(new Date());
        news.getCommentList().add(comment1);
        news.setCommentCount(news.getCommentList().size());
        news.save();

在这里插入图片描述
*也可存储集合

List<News> newsList;
...
 LitePal.saveAll(newsList);

(2)更新
有两种方式:
方式一:使用ContentValue

 ContentValues values = new ContentValues();
        values.put("title","test1");//title 列名
        LitePal.update(News.class,values,1);//1 是更新列的id
        //LitePal.update(News.class,values);//更新所有

条件更新:

 ContentValues values = new ContentValues();
        values.put("title","test2");       
        LitePal.updateAll(News.class, values, "title = ? and commentcount > ?", "test1", "0");

方法二:数据直接更新

  News updateNews = new News();
        updateNews.setTitle("test0");
        updateNews.update(1);//id

条件更新:

        News updateNews = new News();
        updateNews.setTitle("test1");
        updateNews.updateAll("title = ? and commentcount > ?", "test0", "0");

注意:如果要恢复默认值使用setToDefault ,set 0无效

 News updateNews = new News();
        updateNews.setToDefault("commentCount");//commentCount列恢复默认值
        updateNews.updateAll();

(3)删除
删除数据的同时,会把该列id作为外键的关联表的数据一起删除

 int deleteCount = LitePal.delete(News.class, 1);//id 1
  // LitePal.deleteAll(News.class, "title = ? and commentcount = ?", "test1", "0");

判断持久化方法,即是否存到数据库

if (news.isSaved()) {
	news.delete();
}

(4)查询
*查询第一个或最后一个

News firstNews = LitePal.findFirst(News.class);       
News lastNews = LitePal.findLast(News.class);

*按照多个id查询

 List<News> newsList = LitePal.findAll(News.class, 0, 2);
//方法二
long[] ids = new long[] { 0, 1};
List<News> newsList2 = LitePal.findAll(News.class, ids);

*按照条件查询

 //查询news表,条件为commentcount >0 ,只要 title content列的数据 ,降序 ,limit(10) 前10条 ,offset(10)偏移量10 即11-20条数据
        List<News> newsList3 = LitePal.select("title", "content")
                .where("commentcount > ?", "0")
                .order("publishdate desc").limit(10).offset(10)
                .find(News.class);

激进查询
方法一:设置为true,查出news关联表的数据,不推荐,比较慢

 News news = LitePal.find(News.class, 1, true);
        List<Comment> commentList = news.getCommentList();

方法二:News表增加getComments()方法。然后需要时再获取list


public class News extends LitePalSupport{
	
	... 
	public List<Comment> getComments() {
        return LitePal.where("news_id = ?", String.valueOf(id)).find(Comment.class);
    }	
	}

News news2 = LitePal.find(News.class, 1);
        List<Comment> commentList2 = news2.getComments();

*原生查询

 Cursor cursor = LitePal.findBySQL("select * from news where commentcount>?", "0");

4.聚合函数
LitePal中一共提供了count()、sum()、average()、max()和min()这五种聚合函数

        //统计行数
        int result = LitePal.count(News.class);
        // int result1 = LitePal.where("commentcount = ?", "0").count(News.class);
        //结果求和
        int result2 = LitePal.sum(News.class, "commentcount", int.class);
        //结果求平均
        double result3 = LitePal.average(News.class, "commentcount");
        //求最大值
        int result4 = LitePal.max(News.class, "commentcount", int.class);
        //求最小值
        int result5 = LitePal.min(News.class, "commentcount", int.class);

注意:这个框架有个坑,实体类不能实现Parcelable和Serializable,否则在有的手机版本会报

java.lang.NullPointerException
Attempt to invoke virtual method 'java.lang.Class[] java.lang.reflect.Constructor.getParameterTypes()' on a null object reference

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值