今天开发的时候遇到一个用例,简单描述就是在删除一张表里面某条数据的同事,要删除另外的一张表,注意是一张表,而不是记录。
代码实现:
- /**
- * 删除单个对话以及对话包含的消息表
- * @param uuid
- * @return
- */
- public boolean deleteSingleChat(long uuid){
- Statement st = null;
- Database db = super.getsqliteDatabase();
- try {
- db.beginTransaction();
- st = db.createStatement(DELETE_CHAT_sql);
- st.prepare();
- st.bind(1,uuid);
- st.execute();
- st.close();
- st = db.createStatement(DROP_MSG_TABLE + MsgSchema.MSG_TABLE_NAME_HEAD + uuid + ";");
- st.prepare();
- st.execute();
- db.commitTransaction();
- return true;
- } catch (DatabaseException e) {
- return false;
- }finally{
- super.closeStatement(st);
- }
- }
这里需要注意的就是你必须要开启事务来保证业务的一致性。
所以需要
那么在事务中有任何的问题和异常,sqlite都会回滚操作。
- db.beginTransaction();
- .....
- db.commitTransaction();
其次还应该注意对Statment的打开和关闭的时机,请注意,因为我要在事务里面操作两张表,也就是我需要两个Statment
- st = db.createStatement(DROP_MSG_TABLE + MsgSchema.MSG_TABLE_NAME_HEAD + uuid + ";");
- st = db.createStatement(DELETE_CHAT_sql);
那么当我在第一次使用st之后,我必须要st.close(),然后在开启第二个st的时候仍然需要st.prepare();这样才能保证第二次正常的引用st对象。