导入jar ormlite-android-4.48.jar ormlite-core-4.48.jar
新建DatabaseHelper 继承OrmLiteSqliteOpenHelper 1 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 public DatabaseHelper (Context context) { super (context, Constants.Config.DB_NAME, null , Constants.Config.DB_VERSION); } @Override public void onCreate (SQLiteDatabase db, ConnectionSource connectionSource) { createTables(db, connectionSource); } @Override public void onUpgrade (SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) { if (newVersion <= oldVersion) { return ; } try { TableUtils.dropTable(connectionSource,GoldAdvBean.class, true ); } catch (SQLException e) { e.printStackTrace(); db.delete("GOLD_ADV" , null , null ); } createTables(db, connectionSource); } private void createTables (SQLiteDatabase db, ConnectionSource connectionSource) { try { TableUtils.createTableIfNotExists(connectionSource, GoldAdvBean.class); } catch (SQLException e) { e.printStackTrace(); } }
建立操作数据库help单利对象 在Myapplication中建立1 2 3 4 5 6 7 public DatabaseHelper mDatabaseHelper;public DatabaseHelper getDatabaseHelper () { if (mDatabaseHelper == null ) { mDatabaseHelper = new DatabaseHelper(MyApplication.this ); } return mDatabaseHelper; }
建立bean的映射类 1 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 @DatabaseTable (tableName = "GOLD_ADV" , daoClass = GoldAdvBeanDao.class)public class GoldAdvBean implements Parcelable , Serializable { private static final long serialVersionUID = 1L ; @DatabaseField (generatedId = true ) private long Id; @DatabaseField private String imgUrl="" ; @Override public void writeToParcel (Parcel dest, int flags) { dest.writeLong(Id); dest.writeString(imgUrl); } @Override public int describeContents () { return 0 ; } public static Parcelable.Creator<GoldAdvBean> getCreator () { return CREATOR; } public static final Parcelable.Creator<GoldAdvBean> CREATOR = new Creator<GoldAdvBean>() { @Override public GoldAdvBean[] newArray(int size) { return new GoldAdvBean[size]; } @Override public GoldAdvBean createFromParcel (Parcel source) { GoldAdvBean data = new GoldAdvBean(); data.Id = source.readLong(); data.imgUrl = source.readString(); return data; } }; }
使用 1 2 3 4 5 6 7 8 9 10 11 try { GoldAdvBeanDao dao = new GoldAdvBeanDao(myApplication.getDatabaseHelper()); for (int i = 0 ; i < 20 ; i++) { GoldAdvBean goldAdvBean = new GoldAdvBean(); dao.createOrUpdate(goldAdvBean); } List<GoldAdvBean> b=dao.queryForAll(); Log.e("b---->" , b.size()+"" ); } catch (SQLException e) { e.printStackTrace(); }