Sugar ORM——让你不用学SQLite数据库

1.简介

让android数据库操作变得异常简单。

2.基本配置

  1. 配置gradle
    compile 'com.github.satyan:sugar:1.4'

  2. AndroidManifest.xml 配置
    需要重写Application,配置必要参数
    DATABASE:数据库db名字,在/data/data/包名/databases下创建.
    VERSION:版本号
    QUERY_LOG:log信息
    DOMAIN_PACKAGE_NAME:bean所在包路径

<application android:label="@string/app_name" 
android:icon="@drawable/icon"
android:name="com.orm.MyApplication">
.
.
<meta-data android:name="DATABASE" 
android:value="database.db" />
<meta-data android:name="VERSION" 
android:value="1" />
<meta-data android:name="QUERY_LOG" 
android:value="true" />
<meta-data android:name="DOMAIN_PACKAGE_NAME" 
android:value="com.bean" />
.
.
</application>

3.可以使用了

  1. 在相应的bean目录下创建对象并继承SugarRecord。
public class Book {
    String title;
    String author;
    public Book(){
    }
    public Book(String title, String author){
        this.title = title;
        this.author = author;
    }

}
  1. CRUD操作
    • 插入
Book book=new Book("金瓶梅","Alex");
book.save();
  • 查询
//1. list条件查询
 List<Book> books = Book.find(Book.class, "author = ?", new String{"Alex"});
//2. bean条件查询
Book.find(Book.class, "name = ? and anthor = ?", "金瓶梅", "Alex");
//3. 条件查询,以此是分组,排序,limit查询
find(Class<T> type, String whereClause, String[] whereArgs, String groupBy, String orderBy, String limit)
//4. 自定义查询,依然支持查询语句查询
// Could execute other raw queries too here..
Note.executeQuery("VACUUM");
// for finders using raw query.
List<Note> notes = Note.findWithQuery(Note.class, "Select * from Note where name = ?", "satya");


  • 更新
Book book = Book.findById(Book.class, 1);
book.title = "十万个为什么";
book.author = "小偷";
book.save(); 
  • 删除
Book book = Book.findById(Book.class, 1);
book.delete();
  • 删除全部
List<Book> books = Book.listAll(Book.class);
Book.deleteAll(Book.class);
  • *

3.注解

  1. @Table,自定义表明,不以类名为表明,自定义表名,但是你必须定义一个类型为long的id。
  2. @Ignore,即为忽略此属性,不会再数据库中创建相应的字段。
  3. @Column,自定义数据库字段名,例子中不会用author作为字段名,而会用anthor_id作为字段名称。
@Table
public class Book {
    private Long id;
    @Ignore
    String name;
    @Column(name = "author_id", unique = true)
    String author;
    public Book(){
    }
    public Book(String name, String author){
        this.name = name;
        this.author = author;
    }
    public Long getId() {
        return id;
    }
}

最后的一些原则

  1. 属性名字遵循驼峰原则,比如shortName,那么在数据库中的字段名字为short_name.真是因为这个原则,数据库的字段名跟类的属性名不一致,如果想保持一致,可以通过注解@Column修改
  2. Sugar支持一种简单的方式进行数据库升级

    1. 在assets目录下创建一个sugar_upgrades文件夹
    2. 创建文件用 2.sql 3.sql ……命名。
    3. 在AndroidManifest.xml中数据库version中升级版本。如果当前版本为3,那么会执行2.sql 3.sql文件
    4. 在2.sql 3.sql等文件的更新语句示例
      alter table BOOK add ID INTEGER;
  3. 最后附上官方文档的地址http://satyan.github.io/sugar/index.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值