下面列出了android.database.sqlite.SQLiteDatabase#setTransactionSuccessful ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public synchronized void deleteAssignments(Category category) {
SQLiteDatabase database = getWritableDatabase();
database.beginTransaction();
try {
database.execSQL(" UPDATE " + tableName
+ " SET " + AssignmentSchema.STATUS + " = " + Status.DELETED.id + ", "
+ AssignmentSchema.LAST_MODIFIED_TIME + " = ? "
+ " WHERE " + AssignmentSchema.CATEGORY_CODE + " = " + category.getCode()
+ " AND " + AssignmentSchema.USER_ID + " = " + userId,
new String[]{String.valueOf(System.currentTimeMillis())});
database.setTransactionSuccessful();
} finally {
database.endTransaction();
closeDatabase(database);
}
}
public void setAccess(long id, int block) {
lock.writeLock().lock();
try {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransactionNonExclusive();
try {
ContentValues cv = new ContentValues();
cv.put("block", block);
cv.put("allowed", -1);
if (db.update("access", cv, "ID = ?", new String[]{Long.toString(id)}) != 1)
Log.e(TAG, "Set access failed");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} finally {
lock.writeLock().unlock();
}
notifyAccessChanged();
}
@Override
public int delete(List<T> entities) {
int count = 0;
SQLiteDatabase db = getDb(true);
db.beginTransaction();
try {
for (T item : entities) {
count += delete(item);
}
db.setTransactionSuccessful();
} catch (Throwable e) {
e.printStackTrace();
} finally {
db.endTransaction();
}
return count;
}
@Override public void ok() {
SparseArray<Long> deposites = mEnvelopes.getDeposites();
String description = mDescription.getText().toString();
String frequency = null;
int l = deposites.size();
SQLiteDatabase db = (new EnvelopesOpenHelper(getActivity())).getWritableDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
for (int i = 0; i != l; ++i) {
int id = deposites.keyAt(i);
long centsDeposited = deposites.valueAt(i);
EnvelopesOpenHelper.deposite(db, id, centsDeposited, description, frequency);
values.put("lastPaycheckCents", centsDeposited);
db.update("envelopes", values, "_id = ?", new String[] {
Integer.toString(id)
});
}
db.setTransactionSuccessful();
getActivity().getContentResolver().notifyChange(EnvelopesOpenHelper.URI, null);
} finally {
db.endTransaction();
db.close();
}
}
private void executeCreateIndex(SQLiteDatabase db) {
db.beginTransaction();
try {
for (TableInfo tableInfo : Cache.getTableInfos()) {
String[] definitions = SQLiteUtils.createIndexDefinition(tableInfo);
for (String definition : definitions) {
db.execSQL(definition);
}
}
db.setTransactionSuccessful();
}
finally {
db.endTransaction();
}
}
@SuppressWarnings("deprecation")
public static <T> void saveInTx(Collection<T> objects) {
SQLiteDatabase sqLiteDatabase = getSugarDataBase();
try {
sqLiteDatabase.beginTransaction();
sqLiteDatabase.setLockingEnabled(false);
for (T object: objects) {
save(object);
}
sqLiteDatabase.setTransactionSuccessful();
} catch (Exception e) {
Log.i(SUGAR, "Error in saving in transaction " + e.getMessage());
} finally {
sqLiteDatabase.endTransaction();
sqLiteDatabase.setLockingEnabled(true);
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
synchronized (obj) {
SQLiteDatabase db = getDBHelper().getWritableDatabase();
long rowId = 0;
db.beginTransaction();
try {
rowId = db.insert(matchTable(uri), null, values);
db.setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
} finally {
db.endTransaction();
}
if (rowId > 0) {
Uri returnUri = ContentUris.withAppendedId(uri, rowId);
getContext().getContentResolver().notifyChange(uri, null);
return returnUri;
}
throw new SQLException("Failed to insert row into " + uri);
}
}
public int deleteAllMeasurements() {
Timber.d("deleteAllMeasurements(): Deleting all measurements");
SQLiteDatabase db = helper.getWritableDatabase();
db.beginTransaction();
int deletedCellSignals = 0;
try {
deletedCellSignals = db.delete(CellSignalsTable.TABLE_NAME, "1", null);
int deletedMeasurements = db.delete(MeasurementsTable.TABLE_NAME, "1", null);
db.setTransactionSuccessful();
Timber.d("deleteAllMeasurements(): Deleted %s cell signals, %s measurements", deletedCellSignals, deletedMeasurements);
} finally {
invalidateCache();
db.endTransaction();
}
return deletedCellSignals;
}
@Override
public Metrics runCase() {
mDbHelper = new DbHelper(App.getInstance(), IntegerInsertsRawTransactionCase.class.getSimpleName());
Metrics result = new Metrics(getClass().getSimpleName()+" ("+mInsertions+" insertions)", mTestSizeIndex);
SQLiteDatabase db = mDbHelper.getWritableDatabase();
result.started();
db.beginTransaction();
Object[] values = new Object[1];
for (int i = 0; i < mInsertions; i++) {
values[0] = mRandom.nextInt();
db.execSQL("INSERT INTO inserts_1 (val) VALUES (?)", values);
}
db.setTransactionSuccessful();
db.endTransaction();
result.finished();
return result;
}
public void deleteMessageInConversation(Message message) {
long start = SystemClock.elapsedRealtime();
final SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
ContentValues values = new ContentValues();
values.put(Message.DELETED, "1");
String[] args = {message.getUuid()};
int rows = db.update("messages", values, "uuid =?", args);
db.setTransactionSuccessful();
db.endTransaction();
Log.d(Config.LOGTAG, "deleted " + rows + " message in " + (SystemClock.elapsedRealtime() - start) + "ms");
}
@Override
public int deleteAll() throws SQLException {
final SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
int result = 0;
try {
db.beginTransaction();
result = db.delete(mTableName, null, null);
db.setTransactionSuccessful();
} catch (Exception e) {
throw new SQLException(mTableName + " error=" + e, e);
} finally {
db.endTransaction();
}
return result;
}
/**
* Handles requests to insert a set of new rows. In Sunshine, we are only going to be
* inserting multiple rows of data at a time from a weather forecast. There is no use case
* for inserting a single row of data into our ContentProvider, and so we are only going to
* implement bulkInsert. In a normal ContentProvider's implementation, you will probably want
* to provide proper functionality for the insert method as well.
*
* @param uri The content:// URI of the insertion request.
* @param values An array of sets of column_name/value pairs to add to the database.
* This must not be {@code null}.
*
* @return The number of values that were inserted.
*/
@Override
public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
switch (sUriMatcher.match(uri)) {
case CODE_WEATHER:
db.beginTransaction();
int rowsInserted = 0;
try {
for (ContentValues value : values) {
long weatherDate =
value.getAsLong(WeatherContract.WeatherEntry.COLUMN_DATE);
if (!SunshineDateUtils.isDateNormalized(weatherDate)) {
throw new IllegalArgumentException("Date must be normalized to insert");
}
long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, value);
if (_id != -1) {
rowsInserted++;
}
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
if (rowsInserted > 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return rowsInserted;
default:
return super.bulkInsert(uri, values);
}
}
/**
* Initializes the index for the given cache UID.
*
* <p>This method may be slow and shouldn't normally be called on the main thread.
*
* @param uid The cache UID.
* @throws DatabaseIOException If an error occurs initializing the index.
*/
@WorkerThread
public void initialize(long uid) throws DatabaseIOException {
try {
String hexUid = Long.toHexString(uid);
tableName = getTableName(hexUid);
SQLiteDatabase readableDatabase = databaseProvider.getReadableDatabase();
int version =
VersionTable.getVersion(
readableDatabase, VersionTable.FEATURE_CACHE_FILE_METADATA, hexUid);
if (version != TABLE_VERSION) {
SQLiteDatabase writableDatabase = databaseProvider.getWritableDatabase();
writableDatabase.beginTransactionNonExclusive();
try {
VersionTable.setVersion(
writableDatabase, VersionTable.FEATURE_CACHE_FILE_METADATA, hexUid, TABLE_VERSION);
dropTable(writableDatabase, tableName);
writableDatabase.execSQL("CREATE TABLE " + tableName + " " + TABLE_SCHEMA);
writableDatabase.setTransactionSuccessful();
} finally {
writableDatabase.endTransaction();
}
}
} catch (SQLException e) {
throw new DatabaseIOException(e);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.beginTransaction();
doLegacyMigration(db, oldVersion, newVersion);
doAttachmentMigrationTo47(db, oldVersion, newVersion);
doSMSMigrationTo49(db, oldVersion, newVersion);
doRecipientMigrationTo52(db, oldVersion, newVersion);
doRecipientMigrationTo57(db, oldVersion, newVersion);
doRecipientMigrationTo58(db, oldVersion, newVersion);
db.setTransactionSuccessful();
db.endTransaction();
}
public void putBulkItemValue(JsonArray api_data) {
SQLiteDatabase db = null;
SQLiteStatement statement;
try {
if (api_data.size() > 0) {
db = getWritableDatabase();
db.delete(slotitem_table_name, null, null);
db.beginTransaction();
statement = db.compileStatement("INSERT INTO ".concat(slotitem_table_name).concat(" (KEY, KCID, VALUE) values (?, ?, ?)"));
for (JsonElement item: api_data) {
int column = 1;
JsonObject item_data = item.getAsJsonObject();
String api_id = item_data.get("api_id").getAsString();
String api_slotitem_id = item_data.get("api_slotitem_id").getAsString();
statement.bindString(column++, api_id);
statement.bindString(column++, api_slotitem_id);
statement.bindString(column++, item_data.toString());
statement.execute();
}
statement.close();
db.setTransactionSuccessful();
}
} catch (RuntimeException e) {
e.printStackTrace();
} finally {
if (db != null) {
db.endTransaction();
}
}
}
@Override
public void onUpgrade(final SQLiteDatabase database,
final ConnectionSource connectionSource, final int oldVersion, final int newVersion) {
if (oldVersion < 111) {
// Create new Caption table.
try {
TableUtils.createTableIfNotExists(connectionSource, Caption.class);
} catch (SQLException e) {
e.printStackTrace();
}
}
if (oldVersion < 114) {
// Could instead create an ORMLite pojo for topicvideo and do this with TableUtils.
database.execSQL("CREATE TABLE IF NOT EXISTS `topicvideo` (`_id` INTEGER PRIMARY KEY AUTOINCREMENT, `topic_id` VARCHAR, `video_id` VARCHAR )");
}
if (newVersion >= 111) {
// Played with the idea of putting this all into an AsyncTask, but
// 1) Can crash the app. For example, in 114 upgrade we add topicvideo table; if it doesn't exist and user reaches a video list, we
// crash. Worse, if we do crash here the app is broken. Db version has been bumped, so this code doesn't get another chance to run.
// 2) To prevent crash, tried showing AlertDialog. The context we get here is "not an application context", so trying to show a window
// (or sometimes a toast) crashes us with a null window token error. I dug deep to try to pass in a useful context with no luck.
// See branch temp/pass_context_to_helper.
// 3) It doesn't take very long (truncate / reload full video and topic tables is just a few seconds, not long enough for ANR on Fire HD)
new DatabaseImporter(context).import_(DATABASE_RESOURCE_ID, "temp");
SQLiteDatabase tempDb = new TempHelper(context).getReadableDatabase();
if (oldVersion < 111) {
do111Upgrade(database, tempDb);
}
if (oldVersion < 114 && newVersion >= 114) {
// add topicvideo table
do114Upgrade(database, tempDb);
}
if (oldVersion < 120 && newVersion >= 120) {
// add video.dlm_id column
do120Upgrade(database, tempDb);
}
tempDb.close();
context.deleteDatabase(TempHelper.DB_NAME);
// Update download status from storage. This recovers any lost during library updates in 1.1.3.
database.beginTransaction();
try {
for (String yid : getAllDownloadedYoutubeIds()) {
database.execSQL("update video set download_status=? where youtube_id=?", new Object[] {Video.DL_STATUS_COMPLETE, yid});
}
database.setTransactionSuccessful();
} finally {
database.endTransaction();
}
}
}
@Override
public int update(Uri uri, ContentValues contentValues, String selection, String[] selectionArgs) {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
int rowsUpdated;
switch (match) {
case SHOP:
db.beginTransaction();
try {
rowsUpdated = db.update(WoodminContract.ShopEntry.TABLE_NAME, contentValues, selection,
selectionArgs);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
break;
case ORDER:
db.beginTransaction();
try {
rowsUpdated = db.update(WoodminContract.OrdersEntry.TABLE_NAME, contentValues, selection,
selectionArgs);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
break;
case PRODUCT:
db.beginTransaction();
try {
rowsUpdated = db.update(WoodminContract.ProductEntry.TABLE_NAME, contentValues, selection,
selectionArgs);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
break;
case CONSUMER:
db.beginTransaction();
try {
rowsUpdated = db.update(WoodminContract.CustomerEntry.TABLE_NAME, contentValues, selection,
selectionArgs);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
break;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
//getContext().getContentResolver().notifyChange(uri, null, false);
return rowsUpdated;
}
@Override
public void load(
HashMap<String, CachedContent> content, SparseArray<@NullableType String> idToKey)
throws IOException {
Assertions.checkState(pendingUpdates.size() == 0);
try {
int version =
VersionTable.getVersion(
databaseProvider.getReadableDatabase(),
VersionTable.FEATURE_CACHE_CONTENT_METADATA,
hexUid);
if (version != TABLE_VERSION) {
SQLiteDatabase writableDatabase = databaseProvider.getWritableDatabase();
writableDatabase.beginTransaction();
try {
initializeTable(writableDatabase);
writableDatabase.setTransactionSuccessful();
} finally {
writableDatabase.endTransaction();
}
}
try (Cursor cursor = getCursor()) {
while (cursor.moveToNext()) {
int id = cursor.getInt(COLUMN_INDEX_ID);
String key = cursor.getString(COLUMN_INDEX_KEY);
byte[] metadataBytes = cursor.getBlob(COLUMN_INDEX_METADATA);
ByteArrayInputStream inputStream = new ByteArrayInputStream(metadataBytes);
DataInputStream input = new DataInputStream(inputStream);
DefaultContentMetadata metadata = readContentMetadata(input);
CachedContent cachedContent = new CachedContent(id, key, metadata);
content.put(cachedContent.key, cachedContent);
idToKey.put(cachedContent.id, cachedContent.key);
}
}
} catch (SQLiteException e) {
content.clear();
idToKey.clear();
throw new DatabaseIOException(e);
}
}
@SuppressWarnings("deprecation")
private void upgradeFrom4To5(SQLiteDatabase db) {
// remove "persisted" column and rename "isTransient" to "started", add "transient" column for O
try {
db.beginTransaction();
String newTable = JOB_TABLE_NAME + "_new";
db.execSQL("create table " + newTable + " ("
+ COLUMN_ID + " integer primary key, "
+ COLUMN_TAG + " text not null, "
+ COLUMN_START_MS + " integer, "
+ COLUMN_END_MS + " integer, "
+ COLUMN_BACKOFF_MS + " integer, "
+ COLUMN_BACKOFF_POLICY + " text not null, "
+ COLUMN_INTERVAL_MS + " integer, "
+ COLUMN_REQUIREMENTS_ENFORCED + " integer, "
+ COLUMN_REQUIRES_CHARGING + " integer, "
+ COLUMN_REQUIRES_DEVICE_IDLE + " integer, "
+ COLUMN_EXACT + " integer, "
+ COLUMN_NETWORK_TYPE + " text not null, "
+ COLUMN_EXTRAS + " text, "
+ COLUMN_NUM_FAILURES + " integer, "
+ COLUMN_SCHEDULED_AT + " integer, "
+ COLUMN_STARTED + " integer, "
+ COLUMN_FLEX_MS + " integer, "
+ COLUMN_FLEX_SUPPORT + " integer, "
+ COLUMN_LAST_RUN + " integer);");
db.execSQL("INSERT INTO " + newTable + " SELECT "
+ COLUMN_ID + ","
+ COLUMN_TAG + ","
+ COLUMN_START_MS + ","
+ COLUMN_END_MS + ","
+ COLUMN_BACKOFF_MS + ","
+ COLUMN_BACKOFF_POLICY + ","
+ COLUMN_INTERVAL_MS + ","
+ COLUMN_REQUIREMENTS_ENFORCED + ","
+ COLUMN_REQUIRES_CHARGING + ","
+ COLUMN_REQUIRES_DEVICE_IDLE + ","
+ COLUMN_EXACT + ","
+ COLUMN_NETWORK_TYPE + ","
+ COLUMN_EXTRAS + ","
+ COLUMN_NUM_FAILURES + ","
+ COLUMN_SCHEDULED_AT + ","
+ COLUMN_TRANSIENT_OLD + ","
+ COLUMN_FLEX_MS + ","
+ COLUMN_FLEX_SUPPORT + ","
+ COLUMN_LAST_RUN + " FROM " + JOB_TABLE_NAME);
db.execSQL("DROP TABLE " + JOB_TABLE_NAME);
db.execSQL("ALTER TABLE " + newTable + " RENAME TO " + JOB_TABLE_NAME);
db.execSQL("alter table " + JOB_TABLE_NAME + " add column " + COLUMN_TRANSIENT + " integer;");
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
/**
* Ordinarily, if a column is no longer used, we'd err on the side of just leaving it in the
* database but stop referring to it in Java. However because it forms part of the primary
* key of this table, we need to change the primary key to something which _is_ used. Thus,
* this function will rename the old table, create the new table, and then insert all of the
* data from the old into the new with the new primary key.
*/
private void removeApkPackageNameColumn(SQLiteDatabase db, int oldVersion) {
if (oldVersion < 59) {
Utils.debugLog(TAG, "Changing primary key of " + ApkTable.NAME + " from package + vercode to app + vercode + repo");
db.beginTransaction();
try {
// http://stackoverflow.com/questions/805363/how-do-i-rename-a-column-in-a-sqlite-database-table#805508
String tempTableName = ApkTable.NAME + "__temp__";
db.execSQL("ALTER TABLE " + ApkTable.NAME + " RENAME TO " + tempTableName + ";");
String createTableDdl = "CREATE TABLE " + ApkTable.NAME + " ( "
+ ApkTable.Cols.APP_ID + " integer not null, "
+ ApkTable.Cols.VERSION_NAME + " text not null, "
+ ApkTable.Cols.REPO_ID + " integer not null, "
+ ApkTable.Cols.HASH + " text not null, "
+ ApkTable.Cols.VERSION_CODE + " int not null,"
+ ApkTable.Cols.NAME + " text not null, "
+ ApkTable.Cols.SIZE + " int not null, "
+ ApkTable.Cols.SIGNATURE + " string, "
+ ApkTable.Cols.SOURCE_NAME + " string, "
+ ApkTable.Cols.MIN_SDK_VERSION + " integer, "
+ ApkTable.Cols.TARGET_SDK_VERSION + " integer, "
+ ApkTable.Cols.MAX_SDK_VERSION + " integer, "
+ ApkTable.Cols.REQUESTED_PERMISSIONS + " string, "
+ ApkTable.Cols.FEATURES + " string, "
+ ApkTable.Cols.NATIVE_CODE + " string, "
+ ApkTable.Cols.HASH_TYPE + " string, "
+ ApkTable.Cols.ADDED_DATE + " string, "
+ ApkTable.Cols.IS_COMPATIBLE + " int not null, "
+ ApkTable.Cols.INCOMPATIBLE_REASONS + " text, "
+ "PRIMARY KEY (" + ApkTable.Cols.APP_ID + ", " + ApkTable.Cols.VERSION_CODE + ", " + ApkTable.Cols.REPO_ID + ")"
+ ");";
db.execSQL(createTableDdl);
String nonPackageNameFields = TextUtils.join(", ", new String[]{
ApkTable.Cols.APP_ID,
ApkTable.Cols.VERSION_NAME,
ApkTable.Cols.REPO_ID,
ApkTable.Cols.HASH,
ApkTable.Cols.VERSION_CODE,
ApkTable.Cols.NAME,
ApkTable.Cols.SIZE,
ApkTable.Cols.SIGNATURE,
ApkTable.Cols.SOURCE_NAME,
ApkTable.Cols.MIN_SDK_VERSION,
ApkTable.Cols.TARGET_SDK_VERSION,
ApkTable.Cols.MAX_SDK_VERSION,
ApkTable.Cols.REQUESTED_PERMISSIONS,
ApkTable.Cols.FEATURES,
ApkTable.Cols.NATIVE_CODE,
ApkTable.Cols.HASH_TYPE,
ApkTable.Cols.ADDED_DATE,
ApkTable.Cols.IS_COMPATIBLE,
ApkTable.Cols.INCOMPATIBLE_REASONS,
});
String insertSql = "INSERT INTO " + ApkTable.NAME +
"(" + nonPackageNameFields + " ) " +
"SELECT " + nonPackageNameFields + " FROM " + tempTableName + ";";
db.execSQL(insertSql);
db.execSQL("DROP TABLE " + tempTableName + ";");
// Now that the old table has been dropped, we can create indexes again.
// Attempting this before dropping the old table will not work, because the
// indexes exist on the _old_ table, and so are unable to be added (with the
// same name) to the _new_ table.
ensureIndexes(db);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
}