private int deleteMessages(SQLiteDatabase db, String selection, String[] selectionArgs) { int count = 0; String sqlDesc = ""; db.beginTransaction(); try { // Delete all related records from MyDatabase.MsgOfUser for these messages String selectionG = " EXISTS (" + "SELECT * FROM " + Msg.TABLE_NAME + " WHERE (" + Msg.TABLE_NAME + "." + BaseColumns._ID + "=" + MsgOfUser.TABLE_NAME + "." + MyDatabase.MsgOfUser.MSG_ID + ") AND (" + selection + "))"; String descSuffix = "; args=" + Arrays.toString(selectionArgs); sqlDesc = selectionG + descSuffix; count = db.delete(MsgOfUser.TABLE_NAME, selectionG, selectionArgs); // Now delete messages themselves sqlDesc = selection + descSuffix; count = db.delete(Msg.TABLE_NAME, selection, selectionArgs); db.setTransactionSuccessful(); } catch (Exception e) { MyLog.d(TAG, "; SQL='" + sqlDesc + "'", e); } finally { db.endTransaction(); } return count; }
public boolean deleteAll() { boolean flag = false; String deleteHeadSql = "DELETE FROM ProductGroupHead"; String deleteDetailSql = "DELETE FROM ProductGroupDetail"; SQLiteDatabase db = AssetsDatabaseManager.getManager().getDatabase(); try { // 开启事务 db.beginTransaction(); SQLiteStatement detail_stat = db.compileStatement(deleteDetailSql); detail_stat.executeUpdateDelete(); SQLiteStatement head_stat = db.compileStatement(deleteHeadSql); head_stat.executeUpdateDelete(); // 数据插入成功,设置事物成功标志 db.setTransactionSuccessful(); // 保存数据 db.endTransaction(); flag = true; } catch (SQLException e) { // 结束事物,在这里没有设置成功标志,结束后不保存 ZillionLog.e(this.getClass().getName(), e.getMessage(), e); db.endTransaction(); e.printStackTrace(); } return flag; }
/** * Update a Tag * * @param tagID id of tag to update * @param newName new name of tag * @param color new color of tag * @return true if update succeeded, false if failed and transaction rolled back */ public boolean updateTag(int tagID, String newName, String color) throws IllegalArgumentException, SQLiteConstraintException { if (LOG_ON) Log.v("DB.updateTag", "update tagId=" + tagID); if (hasNoChars(newName) || hasNoChars(color) || tagID < 1) { if (LOG_ON) Log.e("db.updateTag", "Invalid argument"); throw new IllegalArgumentException(); } int affected = 0; ContentValues updateValue = new ContentValues(); updateValue.put(TagConst.NAME, newName); updateValue.put(TagConst.COLOR, color); String whereClause = TagConst.ID + "=" + tagID; db.beginTransaction(); affected = db.updateWithOnConflict( TagConst.TBL_NAME, updateValue, whereClause, null, SQLiteDatabase.CONFLICT_ROLLBACK); if (affected > 0) { db.setTransactionSuccessful(); db.endTransaction(); return true; } else { db.endTransaction(); throw new SQLiteConstraintException(); } }
@Override public byte[] getBytes(Object... key) { if (FAKE) return null; SQLiteDatabase db = getWritableDatabase(); String k = Util.concatenate(key); db.beginTransaction(); Cursor c = db.query( TABLE, new String[] {VALUE_COLUMN}, SELECTOR, new String[] {name(), k}, null, null, null); int count = c.getCount(); if (count == 0) { c.close(); db.endTransaction(); return null; } if (count > 1) { c.close(); db.endTransaction(); throw new BException("More than one row:" + k, null); } c.moveToFirst(); byte[] blob = c.getBlob(c.getColumnIndex(VALUE_COLUMN)); c.close(); db.endTransaction(); return blob; }
public void update(Routine updatedRoutine) throws Exception { SQLiteDatabase database = dbHelper.getWritableDatabase(); database.beginTransaction(); try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.UK); Date date = new Date(); ContentValues values = new ContentValues(); int routineId = updatedRoutine.getId(); String[] whereArgs = new String[] {Integer.toString(routineId)}; values.put(DbHelper.ROUTINE_NAME, updatedRoutine.getName()); values.put(DbHelper.ROUTINE_DATE_UPDATED, dateFormat.format(date)); database.update(DbHelper.ROUTINES, values, DbHelper.ROUTINE_ID + "=?", whereArgs); values.clear(); database.delete(DbHelper.STEPS, DbHelper.STEP_ROUTINE_ID + "=?", whereArgs); saveSteps(updatedRoutine, database); database.setTransactionSuccessful(); } catch (Exception e) { database.endTransaction(); database.close(); throw e; } database.endTransaction(); database.close(); }
@Override public void onUpgrade(SQLiteDatabase db, int from, int to) { if (from < 2) { db.execSQL(CREATE_HIERARCHY); db.beginTransaction(); Cursor c = db.query(DICT_TABLE, null, null, null, null, null, null); while (!c.isLast()) { c.moveToNext(); long id = c.getLong(c.getColumnIndex(DICT_COL_ID)); ContentValues val = new ContentValues(); val.put(HIER_COL_ANCESTOR, id); val.put(HIER_COL_DESCENDANT, id); val.put(HIER_COL_LENGTH, 0); db.insert(HIER_TABLE, null, val); } db.setTransactionSuccessful(); db.endTransaction(); } if (from < 3) { db.beginTransaction(); ContentValues val = new ContentValues(); val.put(VocardsDS.DICT_COL_MODIFIED, System.currentTimeMillis()); db.update(VocardsDS.DICT_TABLE, val, VocardsDS.DICT_COL_MODIFIED + " IS NULL", null); db.setTransactionSuccessful(); db.endTransaction(); } if (from < 4) { VocardsDSMigrator.version4(db); } }
/** * 批量增加产品组合主表记录数据 * * @param list */ public boolean batchAddProductGroupHead(List<ProductGroupHeadData> list) { boolean flag = false; String headSql = "insert into ProductGroupHead(PG1_ID,PG1_M02_ID,PG1_CU1_ID,PG1_CODE,PG1_Name,PG1_CreateUser,PG1_CreateTime,PG1_ModifyUser,PG1_ModifyTime,PG1_RowVersion)" + "values(?,?,?,?,?,?,?,?,?,?)"; String detailSql = "insert into ProductGroupDetail(PG2_ID,PG2_M02_ID,PG2_PG1_ID,PG2_PD1_ID,PG2_GroupQty,PG2_CreateUser,PG2_CreateTime,PG2_ModifyUser,PG2_ModifyTime,PG2_RowVersion)" + "values(?,?,?,?,?,?,?,?,?,?)"; SQLiteDatabase db = AssetsDatabaseManager.getManager().getDatabase(); try { // 开启事务 db.beginTransaction(); for (ProductGroupHeadData productGroupHead : list) { SQLiteStatement stat = db.compileStatement(headSql); stat.bindString(1, productGroupHead.getPg1Id()); stat.bindString(2, productGroupHead.getPg1M02Id()); stat.bindString(3, productGroupHead.getPg1Cu1Id()); stat.bindString(4, productGroupHead.getPg1Code()); stat.bindString(5, productGroupHead.getPg1Name()); stat.bindString(6, productGroupHead.getPg1CreateUser()); stat.bindString(7, productGroupHead.getPg1CreateTime()); stat.bindString(8, productGroupHead.getPg1ModifyUser()); stat.bindString(9, productGroupHead.getPg1ModifyTime()); stat.bindString(10, productGroupHead.getPg1RowVersion()); stat.executeInsert(); List<ProductGroupDetailData> children = productGroupHead.getChildren(); if (children != null) { for (ProductGroupDetailData productGroupDetail : children) { SQLiteStatement detail_stat = db.compileStatement(detailSql); detail_stat.bindString(1, productGroupDetail.getPg2Id()); detail_stat.bindString(2, productGroupDetail.getPg2M02Id()); detail_stat.bindString(3, productGroupDetail.getPg2Pg1Id()); detail_stat.bindString(4, productGroupDetail.getPg2Pd1Id()); detail_stat.bindLong(5, productGroupDetail.getPg2GroupQty()); detail_stat.bindString(6, productGroupDetail.getPg2CreateUser()); detail_stat.bindString(7, productGroupDetail.getPg2CreateTime()); detail_stat.bindString(8, productGroupDetail.getPg2ModifyUser()); detail_stat.bindString(9, productGroupDetail.getPg2ModifyTime()); detail_stat.bindString(10, productGroupDetail.getPg2RowVersion()); detail_stat.executeInsert(); } } } // 数据插入成功,设置事物成功标志 db.setTransactionSuccessful(); // 保存数据 db.endTransaction(); flag = true; } catch (SQLException e) { // 结束事物,在这里没有设置成功标志,结束后不保存 ZillionLog.e(this.getClass().getName(), e.getMessage(), e); db.endTransaction(); e.printStackTrace(); } return flag; }
public int bulkInsert(Uri uri, ContentValues[] values) { SQLiteDatabase writeToDatabase = databaseHelper.getWritableDatabase(); int insertedRecords = 0; final int match = matcher.match(uri); switch (match) { case CITY: writeToDatabase.beginTransaction(); try { for (ContentValues value : values) { long insertRecord = writeToDatabase.insert(DatabaseContract.CityInfo.TABLE_NAME, null, value); if (insertRecord > 0) { ContentUris.withAppendedId(uri, insertRecord); Log.v( LOG_CAT, "*** Inserted City Record is: " + ContentUris.withAppendedId(uri, insertRecord)); insertedRecords++; } else { Log.v(LOG_CAT, "*** No City records to Insert"); } } writeToDatabase.setTransactionSuccessful(); } finally { writeToDatabase.endTransaction(); } getContext().getContentResolver().notifyChange(uri, null); break; case ALL_RECORDS: writeToDatabase.beginTransaction(); try { for (ContentValues records : values) { long insertRecord = writeToDatabase.insert(DatabaseContract.ClassInfo.TABLE_NAME, null, records); if (insertRecord > 0) { ContentUris.withAppendedId(uri, insertRecord); Log.v( LOG_CAT, "*** Inserted Record is: " + ContentUris.withAppendedId(uri, insertRecord)); insertedRecords++; } else { Log.v(LOG_CAT, "*** No records to Insert"); } } writeToDatabase.setTransactionSuccessful(); } finally { writeToDatabase.endTransaction(); } getContext().getContentResolver().notifyChange(uri, null); break; default: return super.bulkInsert(uri, values); } return insertedRecords; }
public DatabaseAdapter rollbackTransaction() { mDb.endTransaction(); close(); return this; }
/** update the level and count for the given flashcard in the database. */ private void updateFlashcard(Flashcard fc) { openDB(); _curDB.beginTransaction(); try { // Delete old entry if any. SQLiteStatement dStmt = getCompiledStatement(SQL_DELETE_FCS); dStmt.bindString(1, fc.getLang1Str()); dStmt.execute(); // insert new state entry. SQLiteStatement iStmt = getCompiledStatement(SQL_INSERT_FCS); iStmt.bindString(1, fc.getLang1Str()); iStmt.bindLong(2, fc.getLevel()); iStmt.bindLong(3, fc.getRightGuessCount()); iStmt.execute(); _curDB.setTransactionSuccessful(); } catch (SQLException e) { MsgDispatcher.sendMessageToUI( MsgType.MSG_SHOW_ERROR_MSG, 0, 0, "unable to update id=" + fc.getID()); } finally { _curDB.endTransaction(); } // this flashcard is no longer used by anyone so release it. fc.release(); }
/** Insert a set of flashcards (linked list) in a single transaction. */ private void insertFlashcardSet(Flashcard head) { openDB(); SQLiteStatement stmt = getCompiledStatement(SQL_INSERT_FC); boolean gotError = false; _curDB.beginTransaction(); try { for (Flashcard fc = head; fc != null; fc = Flashcard.Chain.getNext(fc)) { stmt.bindLong(1, _importState.getRandomId()); stmt.bindString(2, fc.getLang1Str()); stmt.bindString(3, fc.getLang2Str()); stmt.execute(); } _curDB.setTransactionSuccessful(); } catch (SQLException e) { gotError = true; MsgDispatcher.sendMessageToUI(MsgType.MSG_SHOW_ERROR_MSG, 0, 0, "unable to insert fc"); } finally { _curDB.endTransaction(); } Flashcard.Chain.releaseChain(head); // tell controller to send us more data if insert went fine. if (!gotError) { MsgDispatcher.sendMessageToController(MsgType.MSG_CONTINUE_IMPORT, 0, 0, null); } }
// from // http://stackoverflow.com/questions/3424156/upgrade-sqlite-database-from-one-version-to-another @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.beginTransaction(); // run a table creation with if not exists (we are doing an upgrade, so the table might // not exists yet, it will fail alter and drop) db.execSQL(getManualBookmarksCreationString()); // put in a list the existing columns List<String> columns = GetColumns(db, "tbl_manual_bookmarks"); // backup table db.execSQL("ALTER TABLE tbl_manual_bookmarks RENAME TO 'temp_tbl_manual_bookmarks'"); // create new table (with new scheme) db.execSQL(getManualBookmarksCreationString()); // get the intersection with the new columns, this time columns taken from the upgraded table columns.retainAll(GetColumns(db, "tbl_manual_bookmarks")); // restore data String cols = joinStrings(columns, ","); db.execSQL( String.format( "INSERT INTO %s (%s) SELECT %s from 'temp_%s", "tbl_manual_bookmarks", cols, cols, "tbl_manual_bookmarks'")); // remove backup table db.execSQL("DROP table 'temp_tbl_manual_bookmarks'"); db.setTransactionSuccessful(); db.endTransaction(); }
public void insertInTable(ArrayList<ArchivoMp3> ListaMp3) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); db.beginTransaction(); try { for (ArchivoMp3 Mp3 : ListaMp3) { values.put("imagen", Mp3.getCaratula()); values.put("artista", Mp3.getBanda()); values.put("album", Mp3.getAlbum()); values.put("cancion", Mp3.getTitulo()); values.put("duracion", Mp3.getDuracion()); values.put("genero", Mp3.getGenero()); values.put("ruta", Mp3.getRuta()); values.put("id_cancion", Mp3.getCancionId()); db.insert("rolas", null, values); } // db.yieldIfContendedSafely(); //keeps the table from locking db.setTransactionSuccessful(); } finally { db.endTransaction(); } db.close(); }
/** * Exec SQL from file in assets * * @param filename * @param db */ protected void execSQLFile(String filename, SQLiteDatabase db) { // get SQL String sql = getSQLFromFile(filename); // check sql if (sql == null || sql.length() == 0) return; // split sql queries String[] queries = sql.split(";"); // begin transaction db.beginTransaction(); try { // iteratate and exec queries for (String query : queries) { db.execSQL(query); } // set transaction successful db.setTransactionSuccessful(); } catch (Exception e) { AppLog.e(e); } finally { // end transaction db.endTransaction(); } }
// 添加player,如果有就更新,没有就添加。 public void add(BubblePlayer player) { db.beginTransaction(); // 开始事务 try { BubblePlayer personInDB = new BubblePlayer(); personInDB = query(player.getId()); // 如果没有找到就直接添加,如果找到了就更新 if (null == personInDB) { db.execSQL( "INSERT INTO starchat_bubbleplayer(id, name, latitude, lontitude, headImg, sex) VALUES(?, ?, ?, ?, ?, ?)", new Object[] { player.getId(), player.getName(), player.getLatitude(), player.getLontitude(), player.getHeadImg(), player.getSex() }); } else { updatePlayer(player); } db.setTransactionSuccessful(); // 设置事务成功完成 } finally { db.endTransaction(); // 结束事务 } }
public static void store(List<Category> categories) { if (categories == null || categories.size() == 0) { return; } SQLiteDatabase database = new ZhihuDatabase(App.getAppContext()).getWritableDatabase(); database.beginTransaction(); boolean newInsert = false; try { for (Category category : categories) { Cursor cursor = database.rawQuery( buildCategoryQueryUri(AppConstant.CATEGORY_EXIST_SQL, category), null); if (cursor == null || cursor.getCount() == 0) { save(category, database); newInsert = true; } IOUtils.close(cursor); } database.setTransactionSuccessful(); if (newInsert) { App.getAppContext() .getContentResolver() .notifyChange(ZhihuProvider.CATEGORY_CONTENT_URI, null); } } catch (Exception e) { Timber.e(e, PersistUtils.class.getSimpleName()); } finally { database.endTransaction(); } // App.getAppContext().getContentResolver().notifyChange(); IOUtils.close(database); }
/** * Removes rows in the smartdial database that matches the contacts that have been deleted by * other apps since last update. * * @param db Database pointer to the dialer database. * @param last_update_time Time stamp of last update on the smartdial database */ private void removeDeletedContacts(SQLiteDatabase db, String last_update_time) { final Cursor deletedContactCursor = mContext .getContentResolver() .query( DeleteContactQuery.URI, DeleteContactQuery.PROJECTION, DeleteContactQuery.SELECT_UPDATED_CLAUSE, new String[] {last_update_time}, null); db.beginTransaction(); try { while (deletedContactCursor.moveToNext()) { final Long deleteContactId = deletedContactCursor.getLong(DeleteContactQuery.DELETED_CONTACT_ID); db.delete( Tables.SMARTDIAL_TABLE, SmartDialDbColumns.CONTACT_ID + "=" + deleteContactId, null); db.delete(Tables.PREFIX_TABLE, PrefixColumns.CONTACT_ID + "=" + deleteContactId, null); } db.setTransactionSuccessful(); } finally { deletedContactCursor.close(); db.endTransaction(); } }
private long update(SQLiteDatabase db, Pista pista) { db.beginTransaction(); try { // save pista int row = db.update( TABLE, getContentValues(pista), Columns._UUID.getColumnName() + " = ? ", new String[] {pista.getUuid()}); // save local pista.getLocal().setUuidLocalizavel(pista.getUuid()); localDAO.save(db, pista.getLocal()); // save horario pista.getHorario().setUuidLocalizavel(pista.getUuid()); horarioDAO.save(db, pista.getHorario()); // save esportes localizavelEsporteDAO.save(db, pista.getUuid(), pista.getEsportes()); db.setTransactionSuccessful(); return row; } catch (Exception ex) { Log.e(TAG, "Error updating pista.", ex); } finally { db.endTransaction(); } return -1; }
public void fillInitialDish() { String cooking = "Салатные листья замочить в холодной воде на 1 час, чтобы они стали свежими и хрустящими.\n" + "Белый хлеб очистить от корочки и порезать на кубики размером примерно 1 сантиметр, затем выложить на противень и подсушить в не слишком горячей духовке.\n" + "В глубокую сковороду налить растительное масло, положить измельченный чеснок. Как только кусочки потемнеют, снять их со сковороды и выложить в масло сухарики. Обжарить до золотистой корочки, выложить на бумажную салфетку для удаления лишнего масла.\n" + "Куриное филе натереть солью и обжарить до готовности, затем остудить и порезать тонкими пластинками.\n" + "Листья салата порвать руками, сыр нарезать тонкими пластинками. Помидоры черри разрезать на четыре части.\n" + "Выложить в салатник все ингредиенты, слегка встряхнуть, чтобы они перемешались, и сразу же подать на стол. Майонез подать отдельно, чтобы каждый едок мог добавлять его по вкусу."; if (db != null) { try { db.beginTransaction(); ContentValues values = new ContentValues(); values.put(Dish.COLUMN_TITLE, "Салат \"Цезарь\" с курицей и сухариками"); values.put(Dish.COLUMN_COOKING, cooking); values.put(Dish.COLUMN_CELEBRATORY, true); values.put(Dish.COLUMN_KIND_ID, 3); db.insert(Dish.TABLE_NAME, null, values); db.setTransactionSuccessful(); Log.i(LOG_TAG, "Dish table filled"); } catch (SQLiteException e) { Log.e(LOG_TAG, e.getMessage()); } finally { db.endTransaction(); } } }
public void nextInstruction(boolean isSucessful, int intented_nextId) { SQLiteDatabase db = app.getDB(); db.beginTransaction(); // deal with current Instruction if (current != null) { markCurrentInstructionState( db, current._id, isSucessful ? Instruction.COMPLETED : Instruction.SKIPPED); intented_nextId = current._id + 1; } Instruction nextInstruction = fetchNextInstruction(db, intented_nextId); if (nextInstruction != null) { // check has nextTask // check if in the same task if (current == null || current.task_id != nextInstruction.task_id) { // app.enterNewTask(current, nextInstruction); app.enterNewTask(nextInstruction.task_id); } boolean switchSegment = (current == null) ? false : (nextInstruction.seg_id > current.seg_id); current = nextInstruction; app.setUserInfomraiton( null, nextInstruction._id, nextInstruction.task_id, nextInstruction.seg_id); if (switchSegment) app.onChangeSegment(); // Log.v("mark", "nextInstruction id:" + nextInstruction); } else { // no more instruction app.enterNewTask(-1); // app.enterNewTask(current, null); current = null; Log.v("mark", "nextInstruction is null"); app.onAllTaskFinished(); } db.setTransactionSuccessful(); db.endTransaction(); }
private void postCorrectVerification() { switch (type) { case DATABASE: { SQLiteDatabase db = app.getDB(); db.beginTransaction(); ContentValues values = new ContentValues(); Cursor cur = db.query(table, null, null, null, null, null, null); int index = cur.getColumnIndex("new"); if (index >= 0) { values.put("new", 0); long result = db.update(table, values, "new = ?", new String[] {"1"}); Log.v("mark", "postCorrectVerification set new to 0 result:" + result); } db.setTransactionSuccessful(); db.endTransaction(); } break; case RIGHTDRAWER: { Activity act = this.app.getCurrentActivity(); if (act != null) { ((FrameActivity) act).clearRightPanel(); } } break; } return; }
public int update(LocalGroup group) { if (isNull(group)) { return -1; } SQLiteDatabase sqLiteDatabase = dbHelper.getWritableDatabase(); sqLiteDatabase.beginTransaction(); int rowsAffected = 0; try { ContentValues values = new ContentValues(); values.put("Group_ID", group.getGroupId()); values.put("SP_Group_ID", group.getSpGroupId()); values.put("Remote_Group_ID", group.getRemoteGroupId()); values.put("Group_Name", group.getName()); long createTime = (group.getCreatedAt() == null ? 0 : group.getCreatedAt().getTime()); values.put("Created_At", createTime); values.put("State", group.getState()); values.put("Account_ID", group.getAccountId()); rowsAffected = sqLiteDatabase.update(TABLE, values, "Group_ID = " + group.getGroupId(), null); sqLiteDatabase.setTransactionSuccessful(); } finally { sqLiteDatabase.endTransaction(); } return rowsAffected; }
/** * Inserts a new entry in the database, if there is no entry for the given date yet. Use this * method for restoring data from a backup. * * <p>This method does nothing if there is already an entry for 'date'. * * @param date the date in ms since 1970 * @param steps the step value for 'date'; must be >= 0 * @return true if a new entry was created, false if there was already an entry for 'date' */ public boolean insertDayFromBackup(long date, int steps) { database.beginTransaction(); boolean re; try { Cursor c = database.query( DB_NAME, new String[] {"date"}, "date = ?", new String[] {String.valueOf(date)}, null, null, null); re = c.getCount() == 0 && steps >= 0; if (re) { ContentValues values = new ContentValues(); values.put("date", date); values.put("steps", steps); database.insert(DB_NAME, null, values); } c.close(); database.setTransactionSuccessful(); } finally { database.endTransaction(); } return re; }
@Override public int bulkInsert(Uri uri, ContentValues[] values) { final SQLiteDatabase db = mOpenHelper.getWritableDatabase(); final int match = sUriMatcher.match(uri); switch (match) { case WEATHER: db.beginTransaction(); int returnCount = 0; try { for (ContentValues value : values) { normalizeDate(value); long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, value); if (_id != -1) { returnCount++; } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } getContext().getContentResolver().notifyChange(uri, null); return returnCount; default: return super.bulkInsert(uri, values); } }
/** * Inserts a new entry in the database, if there is no entry for the given date yet. Steps should * be the current number of steps and it's negative value will be used as offset for the new date. * Also adds 'steps' steps to the previous day, if there is an entry for that date. * * <p>This method does nothing if there is already an entry for 'date' - use {@link #updateSteps} * in this case. * * <p>To restore data from a backup, use {@link #insertDayFromBackup} * * @param date the date in ms since 1970 * @param steps the current step value to be used as negative offset for the new day; must be >= 0 */ public void insertNewDay(long date, int steps) { database.beginTransaction(); try { Cursor c = database.query( DB_NAME, new String[] {"date"}, "date = ?", new String[] {String.valueOf(date)}, null, null, null); if (c.getCount() == 0 && steps >= 0) { ContentValues values = new ContentValues(); values.put("date", date); // use the negative steps as offset values.put("steps", -steps); database.insert(DB_NAME, null, values); // add 'steps' to yesterdays count date -= 24 * 60 * 60 * 1000; updateSteps(date, steps); } c.close(); if (Logger.LOG) { Logger.log("insertDay " + date + " / " + steps); logState(); } database.setTransactionSuccessful(); } finally { database.endTransaction(); } }
public double[][] queryTheCursor(String startdate, String enddate) { double[][] result = new double[][] {}; db.beginTransaction(); // 开始事务 try { try { cursor = db.rawQuery( "SELECT * FROM TempTB2 WHERE _time >= ? AND _time <=?", new String[] {startdate, enddate}); } catch (Exception e) { historyRec = ""; } int count = cursor.getCount(); if (count > 0) { for (int i = 0; i < count; i++) { cursor.moveToNext(); historyRec += "详细日期:" + cursor.getString(2) + "\r\n" + "值:" + cursor.getDouble(1) + "\r\n"; // Yva1.add(cursor.getDouble(1)); result[0][i] = cursor.getDouble(1); result[1][i] = cursor.getDouble(2); // cursor.moveToNext(); } } db.setTransactionSuccessful(); // 设置事务成功完成 } catch (Exception e) { } finally { db.endTransaction(); } return result; }
/** add persons */ public void add(List<BubblePlayer> bubbleplayers) { db.beginTransaction(); // 开始事务 try { for (BubblePlayer player : bubbleplayers) { // db.execSQL("INSERT INTO starchat_bubbleplayer(id, name, latitude, lontitude ) VALUES(5, // 'name', 31, 130)"); BubblePlayer personInDB = new BubblePlayer(); personInDB = query(player.getId()); if (null == personInDB) { db.execSQL( "INSERT INTO starchat_bubbleplayer(id, name, latitude, lontitude, headImg, sex) VALUES(?, ?, ?, ?, ?, ?)", new Object[] { player.getId(), player.getName(), player.getLatitude(), player.getLontitude(), player.getHeadImg(), player.getSex() }); } else { updatePlayer(player); } } db.setTransactionSuccessful(); // 设置事务成功完成 } finally { db.endTransaction(); // 结束事务 } }
private void maybeAddBulletin(BulletinResponse bltn) { maybeAddBlockRef(bltn.blockReference); SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); try { ContentValues values = new ContentValues(); values.put(NewBltnsTable.COLUMN_TXID, bltn.txid); values.put(NewBltnsTable.COLUMN_TIME, bltn.timestamp); values.put(NewBltnsTable.COLUMN_MSG, bltn.msg); values.put(NewBltnsTable.COLUMN_LAT, bltn.loc.lat); values.put(NewBltnsTable.COLUMN_LON, bltn.loc.lon); values.put(NewBltnsTable.COLUMN_H, bltn.loc.h); values.put(NewBltnsTable.COLUMN_AUTHOR, bltn.author); values.put(NewBltnsTable.COLUMN_NUM_ENDOS, bltn.numEndos); values.put(NewBltnsTable.COLUMN_BLOCK_REF, bltn.blockReference.hash); db.insertOrThrow(NewBltnsTable.TABLE_NAME, null, values); db.setTransactionSuccessful(); } catch (Exception e) { } finally { db.endTransaction(); } }
@Override public void addGBActivitySamples(ActivitySample[] activitySamples) { try (SQLiteDatabase db = this.getWritableDatabase()) { String sql = "INSERT INTO " + TABLE_GBACTIVITYSAMPLES + " (" + KEY_TIMESTAMP + "," + KEY_PROVIDER + "," + KEY_INTENSITY + "," + KEY_STEPS + "," + KEY_TYPE + ")" + " VALUES (?,?,?,?,?);"; SQLiteStatement statement = db.compileStatement(sql); db.beginTransaction(); for (ActivitySample activitySample : activitySamples) { statement.clearBindings(); statement.bindLong(1, activitySample.getTimestamp()); statement.bindLong(2, activitySample.getProvider().getID()); statement.bindLong(3, activitySample.getRawIntensity()); statement.bindLong(4, activitySample.getSteps()); statement.bindLong(5, activitySample.getRawKind()); statement.execute(); } db.setTransactionSuccessful(); db.endTransaction(); } }
public boolean getUserByUnamePwd(String username, String password) { db.beginTransaction(); // User u = null; Cursor c = null; try { c = db.rawQuery( "SELECT * FROM user where username = ? and password = ?", new String[] {username, password}); } finally { db.endTransaction(); } if (c != null && c.getCount() > 0) { c.close(); return true; // u = new User(); // System.out.println("====================================================================" // + c.getColumnIndex("_id")); // u.setId(c.getInt(0)); // u.setUsername(username); // u.setPassword(password); // u.setGroupid(c.getInt(c.getColumnIndex("groupid"))); } return false; }