1. SQLite
MydataBaseHelper.java public class MyDatabaseHelper extends SQLiteOpenHelper { //用于创建Book表 public static final String CREATE_BOOK = "create table Book (" + "id integer primary key autoincrement, " + "author text, " + "price real, " + "pages integer, " + "name text, " + "catagory_id integer)"; //用于创建Category表 public static final String CREATE_CATEGORY = "create table Category (" + "id integer primary key autoincrement, " + "category_name text, " + "category_code integer)"; private Context mContext; public MyDatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); mContext = context; } //第一次创建数据库时会调用此方法 @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_BOOK); db.execSQL(CREATE_CATEGORY); } //数据库版本升级时会调用此方法 @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { /*第一版的数据库只有Book表,第二版的数据库增加了Category表, * 为了保证用户体验,在不干扰前一版的数据的情况下,实现对数据 * 库的平滑升级,简单的可以用此方法进行判断在升级*/ switch (oldVersion){ case 1: db.execSQL(CREATE_CATEGORY); case 2: db.execSQL("alter table Book add column category_id integer"); default: } } } 在MainActivity中创建MyDatabaseHelper对象并调用getReadableDatabase( )或者进行数据库的创建getWritableDatabase( ) ,(两者不同点在于,当数据库不可写入时(如磁盘空间已满)getReadableDatabase( )方法返回的对象将以只读的方式去打开数据库,而getWritableDatabase( )方法则将出现异常) //数据库文件名称 private static final String DATABASE_NAME = "BookStore.db"; //数据库版本号private static final int DATABASE_VERSION = 3; private MyDatabaseHelper mMyDatabaseHelper; mMyDatabaseHelper = new MyDatabaseHelper(this, DATABASE_NAME, null, DATABASE_VERSION); mMyDatabaseHelper.getReadableDatabase();
SQLiteDatabase db = mMyDatabaseHelper.getReadableDatabase(); ContentValues values = new ContentValues(); values.put("name", "The Da Vinci Code"); values.put("author", "Dan Brown"); values.put("pages", 454); values.put("price", 16.96); //向数据库插入数据 db.insert("Book", null, values); values.clear(); values.put("name", "The Lost Symbol"); values.put("author", "Dan Brown"); values.put("pages", 510); values.put("price", 19.96); db.insert("Book", null, values); 更新数据库的数据 SQLiteDatabase db = mMyDatabaseHelper.getReadableDatabase(); ContentValues values = new ContentValues(); values.put("price", 10.56); //更新数据库的数据 db.update("Book", values, "name=?", new String[]{"The Da Vinci Code"}); 删除数据库的数据 SQLiteDatabase db = mMyDatabaseHelper.getReadableDatabase(); //删除数据库的数据 db.delete("Book", "pages > ?", new String[]{"500"}); 查询数据(对数据库的查询操作有很多种方式,这里只给出常见的一种) SQLiteDatabase db = mMyDatabaseHelper.getReadableDatabase(); //对数据库表进行查询,会返回游标 Cursor cursor = db.query("Book", null, null, null, null, null, null); while (cursor.moveToNext()){ String name = cursor.getString(cursor.getColumnIndex("name")); String author = cursor.getString(cursor.getColumnIndex("author")); int pages = cursor.getInt(cursor.getColumnIndex("pages")); double price = cursor.getDouble(cursor.getColumnIndex("price")); Log.d("Query BookStore.db", name); Log.d("Query BookStore.db", author); Log.d("Query BookStore.db", pages+""); Log.d("Query BookStore.db", price+""); } cursor.close(); 数据库的事务操作 SQLiteDatabase db = mMyDatabaseHelper.getReadableDatabase(); //开启事务 db.beginTransaction(); try { db.delete("Book", null, null); Toast.makeText(MainActivity.this, 删除数据成功",Toast.LENGTH_SHORT).show(); /*if (true){ throw new NullPointerException(); }*/ ContentValues values = new ContentValues(); values.put("name", "Game of Thrones"); values.put("author", "George Martin"); values.put("pages", 720); values.put("price", 20.15); db.insert("Book", null, values); //事务已经执行成功 db.setTransactionSuccessful(); Toast.makeText(MainActivity.this, "插入数据成功", Toast.LENGTH_SHORT).show(); } catch (NullPointerException e) { e.printStackTrace(); } finally { //结束事务 db.endTransaction(); }
使用:
User.java /* * 当定义表时,第一个建议便是使用final变量定义数据库表名和列名, * 该方法可以简化代码的维护工作,不过本例并没用使用*/ @DatabaseTable(tableName = "tb_user") //@DatabaseTable:标明这是数据库的一张表 public class User { /*@DatabaseField:标明这是表中的字段 columnName: 为该字段在数据中的列名 generatedId:表示id为自增长*/ @DatabaseField(generatedId = true) private int id; @DatabaseField(columnName = "name") private String name; @DatabaseField(columnName = "desc") private String desc; /*ORMLite需要用到无参构造方法 * 当ORMLite需要创建User类时会使用到无参数的构造方法, * 并通过反射机制设置成员变量,也可以使用setter方法设置成员变量*/ public User() { } public User(String name, String desc) { this.name = name; this.desc = desc; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } }
DatabaseHelper.java public class DatabaseHelper extends OrmLiteSqliteOpenHelper { //数据库文件的名称 private static final String TABLE_NAME = "sqlit-test.db"; /*userDao , 每张表对应一个*/ private Dao<User, Integer> userDao; private DatabaseHelper(Context context) { super(context, TABLE_NAME, null, 2); } @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(); } } private static DatabaseHelper instance; /* * 单例获取该Helper*/ public static synchronized DatabaseHelper getHelper(Context context) { if (instance == null){ synchronized (DatabaseHelper.class){ if (instance == null){ instance = new DatabaseHelper(context); } } } return instance; } /* * 获得userDao*/ public Dao<User, Integer> getUserDao() throws SQLException { if (userDao == null){ userDao = getDao(User.class); } return userDao; } /* * 释放资源*/ public void close(){ super.close(); userDao=null; } } 这里我们需要继承OrmLiteSqliteOpenHelper,其实就是间接继承了SQLiteOpenHelper 然后需要实现两个方法:
创建表,我们直接使用ORMLite提供的TableUtils.createTable(connectionSource, User.class);进行创建
//增加数据 public void testAddUser(){ User u1 = new User("zhy", "2B青年"); DatabaseHelper helper = DatabaseHelper.getHelper(getContext()); try{ helper.getUserDao().create(u1); u1 = new User("zhy2", "2B青年"); helper.getUserDao().create(u1); u1 = new User("zhy3", "2B青年"); helper.getUserDao().create(u1); u1 = new User("zhy4", "2B青年"); helper.getUserDao().create(u1); u1 = new User("zhy5", "2B青年"); helper.getUserDao().create(u1); u1 = new User("zhy6", "2B青年"); helper.getUserDao().create(u1); testList(); }catch (SQLException e){ e.printStackTrace(); } } //删除数据 public void testDeleteUser(){ DatabaseHelper helper = DatabaseHelper.getHelper(getContext()); try{ helper.getUserDao().deleteById(2); }catch (SQLException e){ e.printStackTrace(); } } //更新数据 public void testUpdateUser(){ DatabaseHelper helper = DatabaseHelper.getHelper(getContext()); try{ User u1 = new User("zhy-android", "2B青年"); u1.setId(3); helper.getUserDao().update(u1); }catch (SQLException e){ e.printStackTrace(); } } //查询数据 public void testList(){ DatabaseHelper helper = DatabaseHelper.getHelper(getContext()); try { User u1 = new User("zhy-android", "2B青年"); u1.setId(2); List<User> users = helper.getUserDao().queryForAll(); Log.e("TAG", users.toString()); }catch (SQLException e){ e.printStackTrace(); } } (责任编辑:好模板) |