首先:
从 http://ormlite.com/releases/下载对应的核心包core及android支持库.然后在项目中加入两个jar包.
代码就结构图
上面代码下面会有具体的dome供大家参考
重点讲解
1、Ormlite与数据库的映射关系式通过注释来说明的。注释分为对于表的和对于单个列的:@DatabaseTable ,注释表的, @DatabaseField 注释单个列的。
2、DatabaseField
(1)主键:
@DatabaseField(id=true)
(2)列名: 不指定的话就是和变量名一样的
@DatabaseField(columnName="columnName")
(3) 数据类型: 这个一般情况下都不用指定,可以根据java 类获得
@DatabaseField(dataType=DataType.INTEGER)
(4) 默认值:
@DatabaseField(defaultValue="0")
(5)长度:一般用于String型
@DatabaseField(width=13)
(6) 能否为空:默认为True
@DatabaseField(canBeNull=false)
例如代码一:
例如代码二:
像android一样,我们继承这个OrmLiteSqliteOpenHelper工具类。
例如代码三:MainActivity中的使用
public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; DBHelper mDbHelper; Dao<Student, Integer> mStudentDao; Dao<School, Integer> mSchoolDao; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mDbHelper = DBHelper.getInstance(this);//唯一对象 try { mSchoolDao = mDbHelper.getmSchoolDao(); mStudentDao = mDbHelper.getStudentDao(); } catch (java.sql.SQLException e) { e.printStackTrace(); } testDao(); } private void testDao() { //创建两个学生对象、两家学校对象 Student student1 = new Student(); student1.setName("张三"); student1.setId(0); Student student2 = new Student(); student2.setName("李四"); student2.setId(0); School school1 = new School(); school1.setName("家里蹲大学"); school1.setLocation("小李庄"); School school2 = new School(); school2.setName("地里野草拔出学院"); school2.setLocation("大王村"); try { mSchoolDao.create(school1 ); mSchoolDao.create(school2); mStudentDao.create(student1); mStudentDao.create(student2); //获取表中所有的student。 List<Student> students=mStudentDao.queryForAll(); //进行删除student1操作 for (int i = 0; i < students.size(); i++) { Log.e(TAG, students.get(i).getName()); } mStudentDao.delete(student1); //进行查询还剩下什么学生操作 students=mStudentDao.queryForAll(); for (int i = 0; i < students.size(); i++) { Log.e(TAG,"还剩下"+ students.get(i).getName()); } } catch (SQLException e) { e.printStackTrace(); } } // @Override //protected void onDestroy() { // super.onDestroy(); // mDbHelper.close(); // } }
例如代码四:结果
dome地址:http://download.csdn.net/detail/bobo8945510/9613690