创建数据库表结构的实体类.示例代码: @DatabaseTable(tableName = "user")
public class User {
@DatabaseField(generatedId = true)
private int id;
@DatabaseField(columnName = "name")
private String name;
@DatabaseField(columnName = "age")
private int age;
@DatabaseField(columnName = "tel")
private String tel;
public User() {
}
public User(String name, int age, String tel) {
this.name = name;
this.age = age;
this.tel = tel;
}
}
创建OrmLiteSqliteOpenHelper的实现类.示例代码: public class UserDBOpenHelper extends OrmLiteSqliteOpenHelper {
public UserDBOpenHelper(Context context) {
super(context, "user.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
try {
// 创建表
TableUtils.createTable(connectionSource, User.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
// 更新表
TableUtils.dropTable(connectionSource, User.class, true);
onCreate(database, connectionSource);
} catch (SQLException e) {
e.printStackTrace();
}
}
private static UserDBOpenHelper instance;
public static synchronized UserDBOpenHelper getInstance(Context context) {
if (instance == null) {
synchronized (UserDBOpenHelper.class) {
if (instance == null) {
instance = new UserDBOpenHelper(context);
}
}
}
return instance;
}
private Daodao;
// 获取操作数据库的DAO
public DaogetUserDao() throws SQLException {
if (dao == null) {
dao = getDao(User.class);
}
return dao;
}
@Override
public void close() {
super.close();
dao = null;
}
}
获取数据库的DAO对象, 即可进行增删改查的操作.示例代码: UserDBOpenHelper helper = new UserDBOpenHelper(this);
Daodao = helper.getUserDao();
User user = new User("zhangsan", 12, "13212345678");
// 增
dao.create(user);
// 改
dao.updateRaw("update user set tel = '18882348888' where name = ?", new String[]{"王武"});
// 查
Listquery = dao.queryForEq("name", "王武");
// 删
dao.deleteById(2);