步骤:
1.配置
首先去ORMLite官网下载jar包,对于Android为:ormlite-android-4.48.jar 和 ormlite-core-4.48.jar ;
2.创建Bean类
有了jar,我们直接新建一个项目为:zhy_ormlite,然后把jar拷贝到libs下。
然后新建一个包:com.zhy.zhy_ormlite.bean专门用于存放项目中的Bean,首先新建一个User.java
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
package com.zhy.zhy_ormlite.bean;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "tb_user")
public class User
{
@DatabaseField(generatedId = true)
private int id;
@DatabaseField(columnName = "name")
private String name;
@DatabaseField(columnName = "desc")
private String desc;
public User()
{
}
public User(String name, String desc)
{
this.name = name;
this.desc = desc;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getDesc()
{
return desc;
}
public void setDesc(String desc)
{
this.desc = desc;
}
}
|
首先在User类上添加@DatabaseTable(tableName = “tb_user”),标明这是数据库中的一张表,标明为tb_user
然后分别在属性上添加@DatabaseField(columnName = “name”) ,columnName的值为该字段在数据中的列名
@DatabaseField(generatedId = true) ,generatedId 表示id为主键且自动生成
3.创建DAO类,继承 OrmLiteSqliteOpenHelper
原生的数据库操作,需要继承SQLiteOpenHelper,这里我们需要继承OrmLiteSqliteOpenHelper,看代码:
这里我们需要继承OrmLiteSqliteOpenHelper,其实就是间接继承了SQLiteOpenHelper
然后需要实现两个方法:
1、onCreate(SQLiteDatabase database,ConnectionSource connectionSource)
创建表,我们直接使用ormlite提供的TableUtils.createTable(connectionSource, User.class);进行创建~
2、onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion)
更新表,使用ormlite提供的TableUtils.dropTable(connectionSource, User.class, true);进行删除操作~
删除完成后,别忘了,创建操作:onCreate(database, connectionSource);
然后使用单例公布出一个创建实例的方法,getHelper用于获取我们的help实例;
最后我们可能会有很多表嘛,每个表一般我们都会单独写个Dao用于操作,这里为了简单我并没有抽取出来,直接写在helper中:
比如UserDao的获取:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
/**
* 获得userDao
*
* @return
* @throws SQLException
*/
public Dao<User, Integer> getUserDao() throws SQLException
{
if (userDao == null)
{
userDao = getDao(User.class);
}
return userDao;
}
|
然后通过获取到的Dao就可以进行User的一些常用的操作了。
4.创建工具类,实现查询、添加等操作
/**
* 数据库工具类
* @author tarena
*
*/
public class DBUtil {
DBHelper dbHelper;
Dao<CarTypeBain, Integer> dao;
public DBUtil(Context context){
dbHelper = DBHelper.getInstance(context);
try {
dao = dbHelper.getDao(CarTypeBain.class);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//写入汽车信息
public void add(CarTypeBain cb){
try {
dao.createIfNotExists(cb);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//写入一堆汽车信息
public void addAll(List<CarTypeBain> cbs){
for(CarTypeBain cb:cbs){
add(cb);
}
}
//查询城市信息
public List<CarTypeBain> queryAll(){
try {
return dao.queryForAll();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("数据表查询失败!");
}
}
}