时间:2021-07-01 10:21:17 帮助过:39人阅读
自定义OpenHelper类 OpenHelper.java
public class OpenHelper extends OrmLiteSqliteOpenHelper { private Dao<Person, Integer> mPersonDao; public OpenHelper(Context context) { super(context, "test", null, 1);//初始化,数据库名称为test } @Override public void onCreate(SQLiteDatabase sqLiteDatabase, com.j256.ormlite.support.ConnectionSource connectionSource) { try { TableUtils.createTable(connectionSource, Person.class);//根据配置好的实体类建表 } catch (SQLException e) { e.printStackTrace(); } } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, com.j256.ormlite.support.ConnectionSource connectionSource, int i, int i1) { } public Dao<Person, Integer> getPersonDao() throws java.sql.SQLException {//该方法用来返回DAO类 if (mPersonDao == null) { mPersonDao = getDao(Person.class); } return mPersonDao; } }
测试类Test.java
public class Test extends AndroidTestCase { public void testAdd() { Person p1 = new Person("u3"); OpenHelper helper = new OpenHelper(getContext());//新建一个OpenHelper对象 try { helper.getPersonDao().create(p1);//添加一条记录 p1 = new Person("u31"); helper.getPersonDao().create(p1);//添加一条记录 p1 = new Person("u32"); testList();//查询并打出所有记录 } catch (SQLException e) { e.printStackTrace(); } } public void testList() { OpenHelper helper = new OpenHelper(getContext());//建立OpenHelper对象 try { List<Person> users = helper.getPersonDao().queryForAll();//通过DAO来查询所有的记录 Log.v("sk", users.toString());//打印在LOGO之中 } catch (SQLException e) { e.printStackTrace(); } } }
【一个更复杂的例子】
以上就是ORMlite框架的简单用法了,但是这样的用法依然很简陋,如果大家想继续研究的话可以看一下这篇博客
Android 快速开发系列 ORMLite 框架最佳实践
http://blog.csdn.net/lmj623565791/article/details/39122981
【光速使用开源框架系列】数据库框架OrmLite
标签: