Hello.java:
public class Hello{ @DatabaseField(generatedId = true,unique=true) int id; @DatabaseField String word; //这是必须加的,否则会出错 public Hello(){} public int getId() { return id; } public Hello(String word) { super(); this.word = word; } public void setId(int id) { this.id = id; } public String getWord() { return word; } public void setWord(String word) { this.word = word; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("id=").append(id); sb.append(" ,word=").append(word); return sb.toString(); } }
注明:每个字段前面必须@DatabaseField,要不然不能创建这个字段
MainActivity.java:
private void initSqlite(){ SqliteHelper sqliteHelper = new SqliteHelper(this); Dao<Hello, Integer> dao = sqliteHelper.getHelloDao(); // 添加数据 try { for(int i=0;i<3;i++){ Hello hello = new Hello("hello" + i); dao.create(hello); } // 查询添加的数据 List<Hello> hellos = null; hellos = dao.queryForAll(); for (Hello h : hellos){ Log.i(TAG, "-------查询添加的数据 --------"); Log.i(TAG, "word= " + h.getWord()); } //删除数据第一条数据 dao.delete(hellos.get(0)); // 重新查询数据 hellos = dao.queryForAll(); for (Hello h : hellos){ Log.i(TAG, "------- 删除数据第一条数据 --------"); Log.i(TAG, "word= " + h.getWord()); } // 修改数据 Hello h1 = hellos.get(0); h1.setWord("这是修改过的数据"); dao.update(h1); hellos = dao.queryForAll(); for (Hello h : hellos){ Log.i(TAG, "-------修改数据 --------"); Log.i(TAG, "word= " + h.getWord()); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } }
SqliteHelper.java:
public class SqliteHelper extends OrmLiteSqliteOpenHelper{ private static final String TAG = SqliteHelper.class.getSimpleName(); private static final String DATABASE_NAME = "HelloOrmlite.db";//数据库名字 private static final int DATABASE_VERSION = 1;//数据库的版本号 private Dao<Hello, Integer> helloDao = null; public SqliteHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase arg0, ConnectionSource arg1) { try{ TableUtils.createTable(connectionSource, Hello.class); }catch (java.sql.SQLException e) { // TODO Auto-generated catch block Log.i(TAG, "创建数据库失败", e); e.printStackTrace(); } } @Override public void onUpgrade(SQLiteDatabase arg0, ConnectionSource arg1, int arg2, int arg3) { // TODO Auto-generated method stub try{ TableUtils.dropTable(connectionSource, Hello.class, true); onCreate(arg0, connectionSource); }catch (java.sql.SQLException e) { // TODO Auto-generated catch block Log.e(TAG, "更新数据库失败", e); e.printStackTrace(); } } @Override public void close() { // TODO Auto-generated method stub super.close(); helloDao = null; } public Dao<Hello, Integer> getHelloDao() { if (helloDao == null){ try { helloDao = getDao(Hello.class); } catch (java.sql.SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return helloDao; } }