在做一個項目時,遇到一個問題:易英健每分鐘會記錄一比數據,需要用手機掃描,獲取此數據,但每次攜帶過來的數據就會有重復得數據,數據需要每次的重復插入,而每次的更新數量較少(1min一筆),且后續得數據量稍大(存滿會有每次讀取4k筆數據),這樣就會有重復的數據很多,這樣可能會大量的占用內存,減少讀取的速度現在有一個方法能稍作緩解(后續可能會更新刪除重復數據的方法),目前采用的是查詢非重復的數據。
用的是android手機所以都是java代碼,其中數據庫的查詢方法用的是android自帶得sql。難點部分就是查詢部分得篩選,以及刪除多余數據庫的操作(但并不是刪除重復數據的方法)。
首先是查詢部分(插入部分不做解釋)
/** * 查找uid對應的所有的溫度數據 * * @param context db * @param uid 唯一碼 * @return */ public ArrayList<TagTemperature> queryAll(Context context, String uid) { try { SQLiteDatabase db = DatabaseHelper.getDatabaseHelper(context).getWritableDatabase(); //數據集合 ArrayList<TagTemperature> mDatas = new ArrayList<>(); //根據uid篩選出所需要的數據 String selection = "uid=?"; String[] selectionArgs = {uid}; //根據DateTime篩選出非重復數 String groupBy = "DateTime"; String having = null; //查詢 Cursor c = db.query(true, TABLE, null, selection, selectionArgs, groupBy, having, "DateTime" + " DESC", null);// Cursor c = db.query(false, TABLE, null, null, null, null, null, "DateTime" + " DESC", null); int size = c.getCount(); int id = 0; while (c.moveToNext()) { if (c.getPosition() < 50) {//只選擇50筆數據,可調節數值,此處為限定的查詢的數據上限 TagTemperature data = cursorToValue(c); mDatas.add(data); } else { //跳出循環,cursor不動 break; } id = c.getInt(c.getColumnIndex("id")); } LogUtil.info(TAG, "size: " + size + " position: " + c.getPosition()); LogUtil.info(TAG, "DateTime: " + mDatas.get(mDatas.size() - 1).getDate()); //獲得主鍵,根據主鍵刪除超出篩選查詢的部分 LogUtil.info(TAG, "id: " + id); //刪除50以前的數據 deleteTBTemperatureLim(context, id); c.close(); db.close(); return mDatas; } catch (Exception e) { e.PRintStackTrace(); return null; } } 然后是deleteTBTemperatureLim(context,id)方法/** * 刪除標簽50條左右的溫度數據 * * @param context */ public boolean deleteTBTemperatureLim(Context context, int id) { try { //根據時間篩選數據庫中的數據 SQLiteDatabase db = DatabaseHelper.getDatabaseHelper(context).getWritableDatabase(); String whereClause = "id<?"; db.delete(TABLE, whereClause, new String[]{"" + id}); //查詢數據 Cursor cd = db.query(false, TABLE, null, null, null, null, null, "DateTime" + " DESC", null); LogUtil.info(TAG, "size: " + cd.getCount()); //若是表單中本來就沒有重復數據,可直接使用詞語法,刪除想要的上限數據 //sql = "delete from " + TABLE + " where id <= (select max(id) - 50from " + TABLE + ")"; //db.execSQL(sql); return true; } catch (Exception e) { e.printStackTrace(); LogUtil.info(TAG, "error"); return false; } }至此結束附下創建的表單 private final String getTBTemperature() { StringBuffer sb = new StringBuffer(); //表單名DeviceParams sb.append("CREATE Table IF NOT EXISTS TBTemperature("); //primary key sb.append("id integer primary key autoincrement,"); //設備唯一碼 sb.append("uid VarChar(50),"); //貨品名稱 sb.append("GoodsName VarChar(20),"); //時間 sb.append("DateTime time,"); //溫度上限 sb.append("maxTemperature Double,"); //溫度下限 sb.append("minTemperature Double,"); //檢測度數 sb.append("Temperature Double,"); //狀態,是否超出范圍 sb.append("STATUS Integer"); sb.append(")"); return sb.toString(); }
新聞熱點
疑難解答