标签:
SQLite实现基本的增删改查功能
还是向之前一样,先介绍功能,再介绍所用知识点,然后贴下代码。
public class Student { private int id; private String name; private int age; private String info; 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 int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } public Student(int id, String name, int age, String info) { super(); this.id = id; this.name = name; this.age = age; this.info = info; } public Student() { super(); } @Override public String toString() { return "Student [id=" + id + ", name=" + name + ", age=" + age + "]"; } }
2,DBHelper.java,继承SQLiteOpenHelper类
/** * 能够更好的管理和维护数据库,我们会封装一个继承自SQLiteOpenHelper类的数据库操作类, * 然后以这个类为基础,再封装我们的业务逻辑方法。 * @author wk * */ public class DBHelper extends SQLiteOpenHelper { public static final String DB_NAME = "test.db"; public static final int VERSION = 1; public DBHelper(Context context) { //CursorFactory设置为null,使用默认值 super(context, DB_NAME, null, VERSION); } //数据库第一次被创建时onCreate会被调用 @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL("CREATE TABLE IF NOT EXISTS student" + "(_id INTEGER PRIMARY KEY , name VARCHAR, age INTEGER, info TEXT)"); } //如果DATABASE_VERSION值被改为2,系统发现现有数据库版本不同,即会调用onUpgrade @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub // if(oldVersion ==1&&newVersion ==2){ // db.execSQL("alter table student add sex integer"); // } } }
3,数据库管理类DBManager,实现增删改查功能
public class DBManager { private DBHelper helper = null; private SQLiteDatabase database ; public DBManager(Context context) { this.helper = new DBHelper(context); //因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0, mFactory); //所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里 database = helper.getWritableDatabase(); } /** * 插入操作 * 在添加student信息时,我们采用了事务处理,确保数据完整性; * @param student */ public boolean insert(Student student){ boolean flag = false; //开启事务 database.beginTransaction(); try { if(database.isOpen()){ database.execSQL("insert into student(name,age,info) values(?,?,?)",new Object[]{student.getName(),student.getAge(),student.getInfo()} ); //标记事务成功,如果没执行这句话,则自动回滚 database.setTransactionSuccessful(); } flag = true; } catch (Exception e) { // TODO: handle exception e.printStackTrace(); }finally{ //关闭事务 database.endTransaction(); } return flag; } /** * 删除操作 * @param studentId */ public boolean delete(int studentId){ boolean flag = false; try { if(database.isOpen()){ database.execSQL("delete from student where _id = ?",new Object[]{studentId}); } flag = true; } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return flag; } /** * 更新操作 * @param id * @param name * @return */ public boolean update(int id,String name){ boolean flag = false; try { if(database.isOpen()){ database.execSQL("update student set name = ? where _id = ?",new Object[]{name,id}); database.close(); } flag = true; } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return flag; } /** * 根据id查询学生信息 * @param id * @return */ public Student queryById(int id){ Student student = null; try { if(database.isOpen()){ Cursor cursor = database.rawQuery("select _id,name,age,info from student where _id = ?", new String[]{String.valueOf(id)}); if(cursor!=null && cursor.getCount()>0){ if(cursor.moveToFirst()){ int _id =cursor.getInt(0); String name = cursor.getString(1); int age = cursor.getInt(2); String info = cursor.getString(3); student = new Student(_id,name,age,info); } } cursor.close(); } return student; } catch (Exception e) { // TODO: handle exception e.printStackTrace(); return null; } } /** * 查询所有的学生信息 * @return */ public List<Student> queryAllStudent(){ List<Student> studentList = null; try { if(database.isOpen()){ studentList = new ArrayList<Student>(); Cursor cursor = database.rawQuery("select _id,name,age,info from student",null); while (cursor.moveToNext()){ int _id =cursor.getInt(cursor.getColumnIndex("_id")); String name = cursor.getString(cursor.getColumnIndex("name")); int age = cursor.getInt(cursor.getColumnIndex("age")); String info = cursor.getString(cursor.getColumnIndex("info")); Student student = new Student(_id,name,age,info); studentList.add(student); } } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return studentList; } public void closeDB() { //释放数据库连接,否则容易出现SQLiteException if(database.isOpen()){ database.close(); } } }
4,测试类DatabaseTest,继承AndroidTestCase
public class DatabaseTest extends AndroidTestCase { public static final String TAG = DatabaseTest.class.getSimpleName(); private DBManager dao ; public void testInsert(){ Student student = new Student(); student.setName("冠希"); student.setAge(30); student.setInfo("hhe"); dao = new DBManager(getContext()); boolean flag = dao.insert(student); Assert.assertEquals(true, flag); } public void testDelete(){ dao = new DBManager(getContext()); boolean flag = dao.delete(1); Assert.assertEquals(true, flag); } public void testUpdate(){ dao = new DBManager(getContext()); boolean flag = dao.update(1, "凤姐"); Assert.assertEquals(true, flag); } public void testQueryAll(){ dao = new DBManager(getContext()); List<Student> studentList= dao.queryAllStudent(); for (int i = 0; i < studentList.size(); i++) { Log.i(TAG, studentList.get(i).toString()); } } public void testQueryId(){ dao = new DBManager(getContext()); Student student= dao.queryById(2); Log.i(TAG, student.toString()); } }
最后为了JUnit单元测试,需要在AndroidManifest.xml文件中配置一下信息:
标签:
原文地址:http://www.cnblogs.com/wk843620202/p/4413343.html