Ormlite数据库

1. Ormlite是什么?

  • Android原生操作数据库的方式是这样的: 
  • 首先定义一个类继承SQLiteOpenHelper,重写onCreate和onUpdate
  • 后续对数据库的增删改查以及创建和销毁都需要操作相对比较底层的sql语句,难以记忆又容易出错
  • 而且操作sql语句代码量多,sql语句的逻辑比较繁琐
  • 而Java是面向对象的语言,有没有一种方式可以让我们不去关心sql语句的编写,直接面向对象;我们操作对象就间接操作了数据库。那么orm数据库框架就是帮助我们完成这个事,并且能够将javabean和数据库的表映射起来,javabean的字段就是表的字段。这就是为什么叫o(对象)r(关系)m(映射)的原因。
  • Ormlite就是一个orm数据库框架之一。

2. 为什么选择Ormlite?

Andorid平台的orm数据库框架有很多:比如greenDao,DBFlow,Relm等,甚至xutil,afinal;每个orm框架各有优缺点,而Ormlite使用起来非常容易上手,效率也还不错,所以我们选择它作为学习的对象。试想想,如果一个类库光配置就需要搞一天,你还会有心情用它么?

3. Ormlite如何使用?

  • 准备工作:引入相关jar包
  • 首先,定义类继承OrmLiteSqliteOpenHelper:
public class MyDbhepler extends OrmLiteSqliteOpenHelper {
    private static final String TAG = "MyDbhepler";

    public MyDbhepler(Context context) {
        super(context, "ngyb.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        try {
            Log.e(TAG, "onCreate: ");
            TableUtils.createTable(connectionSource, Student.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {

    }
}
  • 其次,编写javabean,通过注解配置和表的映射关系:
@DatabaseTable(tableName = "student")
public class Student {
    public Student() {
        //javabean 一定要创建一个无参数的构造
    }

    public Student(String name) {
        this.name = name;
    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @DatabaseField(generatedId = true)
    public int id;
    @DatabaseField
    public String name;
    @DatabaseField
    public int age;

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
  • 最后,调用dao类的对应方法,直接操作对象,即可完成增删改查:
        MyDbhepler myDbhepler = new MyDbhepler(getApplicationContext());
        try {
            Dao<Student, Integer> dao = myDbhepler.getDao(Student.class);
            Log.e(TAG, "onCreate: ");
            dao.create(new Student("ngyb", 18));
//            Student student = dao.queryForId(0);
            Student student = dao.queryForAll().get(0);
            if (student != null) {
                student.name = "ltz";
                student.age = 23;
                dao.update(student);
            }
            //            dao.deleteById(3);
            List<Student> students = dao.queryForAll();
            for (Student student1 : students) {
                Log.e(TAG, "onCreate: " + student1.toString());
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

}

猜你喜欢

转载自www.cnblogs.com/nangongyibin/p/10421708.html