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

来源:互联网 发布:淘宝店标logo生成器 编辑:程序博客网 时间:2024/06/12 09:39

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作为字段名称。
@Tablepublic 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 0