首先将ormlite的jar包导入项目中,成功后在项目中创建模型MsgBean类
@DatabaseTable(tableName = "t_msg")//表名
public class MsgBean { @DatabaseField(generatedId = true)//表示主键是自动生成的 private int id; @DatabaseField private String number; @DatabaseField private String time;public MsgBean() {
}public int getId() {
return id; }public void setId(int id) {
this.id = id; }public String getNumber() {
return number; }public void setNumber(String number) {
this.number = number; }public String getTime() {
return time; }public void setTime(String time) {
this.time = time; } }数据库操作类 DataBaseHelpr类,代码如下
public class DataBaseHelper extends OrmLiteSqliteOpenHelper {
// 数据库名称,会在程序的目录中生成test_db.db数据库文件 public static String DATABASE_NAME = "test_db"; // 数据库version private static final int DATABASE_VERSION = 1; private static DataBaseHelper instance; public DataBaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public static DataBaseHelper getHelper(Context context){ if (instance==null){ synchronized (DataBaseHelper.class){ if (instance==null){ instance = new DataBaseHelper(context); } } } return instance; }public void close() { super.close(); }
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) { try { // TableUtils.clearTable(connectionSource,MsgBean.class); TableUtils.createTableIfNotExists(connectionSource,UserBean.class); TableUtils.createTableIfNotExists(connectionSource,MsgBean.class); } catch (SQLException e) { e.printStackTrace(); } }@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) { try { // TableUtils.dropTable(connectionSource, MsgBean.class, true); TableUtils.dropTable(connectionSource, UserBean.class, true); onCreate(sqLiteDatabase, connectionSource); } catch (SQLException e) { e.printStackTrace(); } } } 针对t_msg相关的表操作类 MsgDaopublic class MsgDao {
private Dao<MsgBean, Integer> dao;public MsgDao(Context context) {
DataBaseHelper helper = DataBaseHelper.getHelper(context); try { dao = helper.getDao(MsgBean.class); } catch (SQLException e) { e.printStackTrace(); } }public void saveData(MsgBean bean) {
try { dao.create(bean); } catch (SQLException e) { e.printStackTrace(); } }public void delById(int id) {
try { dao.deleteById(id); } catch (SQLException e) { e.printStackTrace(); } }public MsgBean getById(int id) {
try { return dao.queryForId(id); } catch (SQLException e) { e.printStackTrace(); return null; } }public List<MsgBean> getAll() {
try {return dao.queryForAll();
} catch (SQLException e) { e.printStackTrace(); return null; } } } 上述为ormLite的简单使用