数据库开源框架之ormlite
主页: http://ormlite.com/
配置: 添加以下依赖
* compile 'com.j256.ormlite:ormlite-android:4.48'
*
compile 'com.j256.ormlite:ormlite-core:4.48'
用途: 操作数据库
使用步骤
1. 创建数据库表结构的实体类.示例代码:
//指定数据库表名 @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; //java.lang.IllegalArgumentException: Can't find a no-arg constructor for class cn.loaderman.ormlite.User public User() {} public User(String name, int age, String tel) { this.name = name; this.age = age; this.tel = tel; } }
2.创建OrmLiteSqliteOpenHelper的实现类.示例代码:
public class UserDBOpenHelper extends OrmLiteSqliteOpenHelper { /** * 构造方法 * @param context * 上下文 * @param databaseName * 数据库的名称 * @param factory * 游标工厂 * @param databaseVersion * 数据库版本 */ public OrmlitOpenHelper(Context context) { super(context, "user.db", null,1); } /** * 创建数据库的表 */ @Override public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) { try { TableUtils.createTable(connectionSource,User.class); } catch (SQLException e) { e.printStackTrace(); } } /** * 数据库升级调用 */ @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) { try { TableUtils.dropTable(connectionSource,User.class,true); onCreate(sqLiteDatabase,connectionSource); } catch (SQLException e) { e.printStackTrace(); } } }
3. 获取数据库的DAO对象, 即可进行增删改查的操作.示例代码:
UserDBOpenHelper helper = new UserDBOpenHelper(this); Dao<User, Integer> dao = helper.getUserDao(); User user = new User("zhangsan", 12, "13212345678"); // 增 dao.create(user); // 改 dao.updateRaw("update user set tel = '18882348888' where name = ?", new String[]{"zhangsan"}); // 查 List<User> list = dao.queryForAll(); for(User user:list){ System.out.println(user.toString()); } // 删 dao.deleteById(1);
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!