下面列出了怎么用android.database.DatabaseUtils的API类实例代码及写法,或者点击链接到github查看源代码。
int calculateDebugTableInsertionPoint() {
SQLiteDatabase db = mDeDatabase.getReadableDatabase();
String queryCountDebugDbRows = "SELECT COUNT(*) FROM " + TABLE_DEBUG;
int size = (int) DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
if (size < MAX_DEBUG_DB_SIZE) {
return size;
}
// This query finds the smallest timestamp value (and if 2 records have
// same timestamp, the choose the lower id).
queryCountDebugDbRows = "SELECT " + DEBUG_TABLE_KEY +
" FROM " + TABLE_DEBUG +
" ORDER BY " + DEBUG_TABLE_TIMESTAMP + "," + DEBUG_TABLE_KEY +
" LIMIT 1";
return (int) DatabaseUtils.longForQuery(db, queryCountDebugDbRows, null);
}
public static void addFilterKeyword(int type, Collection<String> words) {
DatabaseUtils.InsertHelper ih = new DatabaseUtils.InsertHelper(getWsd(), FilterTable.TABLE_NAME);
final int nameColumn = ih.getColumnIndex(FilterTable.NAME);
final int activeColumn = ih.getColumnIndex(FilterTable.ACTIVE);
final int typeColumn = ih.getColumnIndex(FilterTable.TYPE);
try {
getWsd().beginTransaction();
for (String word : words) {
ih.prepareForInsert();
ih.bind(nameColumn, word);
ih.bind(activeColumn, true);
ih.bind(typeColumn, type);
ih.execute();
}
getWsd().setTransactionSuccessful();
} catch (SQLException e) {
} finally {
getWsd().endTransaction();
ih.close();
}
}
@Override
public void updateRoomMember(long roomId, QiscusRoomMember qiscusRoomMember, String distinctId) {
distinctId = distinctId == null ? "default" : distinctId;
String where = QiscusDb.RoomMemberTable.COLUMN_ROOM_ID + " = " + roomId + " AND "
+ QiscusDb.RoomMemberTable.COLUMN_USER_EMAIL + " = " + DatabaseUtils.sqlEscapeString(qiscusRoomMember.getEmail());
sqLiteWriteDatabase.beginTransactionNonExclusive();
try {
sqLiteWriteDatabase.update(QiscusDb.RoomMemberTable.TABLE_NAME,
QiscusDb.RoomMemberTable.toContentValues(roomId, distinctId, qiscusRoomMember), where, null);
sqLiteWriteDatabase.setTransactionSuccessful();
} catch (Exception e) {
QiscusErrorLogger.print(e);
} finally {
sqLiteWriteDatabase.endTransaction();
}
addOrUpdate(qiscusRoomMember);
}
@Override
public QiscusChatRoom getChatRoomWithUniqueId(String uniqueId) {
String query = "SELECT * FROM "
+ QiscusDb.RoomTable.TABLE_NAME + " WHERE "
+ QiscusDb.RoomTable.COLUMN_UNIQUE_ID + " = " + DatabaseUtils.sqlEscapeString(uniqueId);
Cursor cursor = sqLiteReadDatabase.rawQuery(query, null);
if (cursor.moveToNext()) {
QiscusChatRoom qiscusChatRoom = QiscusDb.RoomTable.parseCursor(cursor);
qiscusChatRoom.setMember(getRoomMembers(qiscusChatRoom.getId()));
QiscusComment latestComment = getLatestComment(qiscusChatRoom.getId());
if (latestComment != null) {
qiscusChatRoom.setLastComment(latestComment);
}
cursor.close();
return qiscusChatRoom;
} else {
cursor.close();
return null;
}
}
/**
* Performs special reinterpretation of certain SQL statements such as "BEGIN",
* "COMMIT" and "ROLLBACK" to ensure that transaction state invariants are
* maintained.
*
* This function is mainly used to support legacy apps that perform their
* own transactions by executing raw SQL rather than calling {@link #beginTransaction}
* and the like.
*
* @param sql The SQL statement to execute.
* @param bindArgs The arguments to bind, or null if none.
* @param connectionFlags The connection flags to use if a connection must be
* acquired by this operation. Refer to {@link SQLiteConnectionPool}.
* @param cancellationSignal A signal to cancel the operation in progress, or null if none.
* @return True if the statement was of a special form that was handled here,
* false otherwise.
*
* @throws SQLiteException if an error occurs, such as a syntax error
* or invalid number of bind arguments.
* @throws OperationCanceledException if the operation was canceled.
*/
private boolean executeSpecial(String sql, Object[] bindArgs, int connectionFlags,
CancellationSignal cancellationSignal) {
if (cancellationSignal != null) {
cancellationSignal.throwIfCanceled();
}
final int type = DatabaseUtils.getSqlStatementType(sql);
switch (type) {
case DatabaseUtils.STATEMENT_BEGIN:
beginTransaction(TRANSACTION_MODE_EXCLUSIVE, null, connectionFlags,
cancellationSignal);
return true;
case DatabaseUtils.STATEMENT_COMMIT:
setTransactionSuccessful();
endTransaction(cancellationSignal);
return true;
case DatabaseUtils.STATEMENT_ABORT:
endTransaction(cancellationSignal);
return true;
}
return false;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
* @author paulburke
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
if (DEBUG)
DatabaseUtils.dumpCursor(cursor);
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
@Override
public int bulkInsert(String callingPkg, Uri url, ContentValues[] values) throws RemoteException {
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
try {
data.writeInterfaceToken(IContentProvider.descriptor);
data.writeString(callingPkg);
url.writeToParcel(data, 0);
data.writeTypedArray(values, 0);
mRemote.transact(IContentProvider.BULK_INSERT_TRANSACTION, data, reply, 0);
DatabaseUtils.readExceptionFromParcel(reply);
int count = reply.readInt();
return count;
} finally {
data.recycle();
reply.recycle();
}
}
@Override
public ContentProviderResult[] applyBatch(String callingPkg,
ArrayList<ContentProviderOperation> operations)
throws RemoteException, OperationApplicationException {
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
try {
data.writeInterfaceToken(IContentProvider.descriptor);
data.writeString(callingPkg);
data.writeInt(operations.size());
for (ContentProviderOperation operation : operations) {
operation.writeToParcel(data, 0);
}
mRemote.transact(IContentProvider.APPLY_BATCH_TRANSACTION, data, reply, 0);
DatabaseUtils.readExceptionWithOperationApplicationExceptionFromParcel(reply);
final ContentProviderResult[] results =
reply.createTypedArray(ContentProviderResult.CREATOR);
return results;
} finally {
data.recycle();
reply.recycle();
}
}
private static void appendValues(final Cursor cursor, final StringBuilder builder, final int skipColumn) {
builder.append("(");
for (int i = 0; i < cursor.getColumnCount(); ++i) {
if (i == skipColumn) {
continue;
}
if (i != 0) {
builder.append(',');
}
final String value = cursor.getString(i);
if (value == null) {
builder.append("NULL");
} else if (value.matches("[0-9]+")) {
builder.append(value);
} else {
DatabaseUtils.appendEscapedSQLString(builder, value);
}
}
builder.append(")");
}
@Override
public int update(String callingPkg, Uri url, ContentValues values, String selection,
String[] selectionArgs) throws RemoteException {
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
try {
data.writeInterfaceToken(IContentProvider.descriptor);
data.writeString(callingPkg);
url.writeToParcel(data, 0);
values.writeToParcel(data, 0);
data.writeString(selection);
data.writeStringArray(selectionArgs);
mRemote.transact(IContentProvider.UPDATE_TRANSACTION, data, reply, 0);
DatabaseUtils.readExceptionFromParcel(reply);
int count = reply.readInt();
return count;
} finally {
data.recycle();
reply.recycle();
}
}
@Override
public Bundle call(String callingPkg, String method, String request, Bundle args)
throws RemoteException {
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
try {
data.writeInterfaceToken(IContentProvider.descriptor);
data.writeString(callingPkg);
data.writeString(method);
data.writeString(request);
data.writeBundle(args);
mRemote.transact(IContentProvider.CALL_TRANSACTION, data, reply, 0);
DatabaseUtils.readExceptionFromParcel(reply);
Bundle bundle = reply.readBundle();
return bundle;
} finally {
data.recycle();
reply.recycle();
}
}
@Override
public String[] getStreamTypes(Uri url, String mimeTypeFilter) throws RemoteException
{
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
try {
data.writeInterfaceToken(IContentProvider.descriptor);
url.writeToParcel(data, 0);
data.writeString(mimeTypeFilter);
mRemote.transact(IContentProvider.GET_STREAM_TYPES_TRANSACTION, data, reply, 0);
DatabaseUtils.readExceptionFromParcel(reply);
String[] out = reply.createStringArray();
return out;
} finally {
data.recycle();
reply.recycle();
}
}
@Override
public AssetFileDescriptor openTypedAssetFile(String callingPkg, Uri url, String mimeType,
Bundle opts, ICancellationSignal signal) throws RemoteException, FileNotFoundException {
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
try {
data.writeInterfaceToken(IContentProvider.descriptor);
data.writeString(callingPkg);
url.writeToParcel(data, 0);
data.writeString(mimeType);
data.writeBundle(opts);
data.writeStrongBinder(signal != null ? signal.asBinder() : null);
mRemote.transact(IContentProvider.OPEN_TYPED_ASSET_FILE_TRANSACTION, data, reply, 0);
DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(reply);
int has = reply.readInt();
AssetFileDescriptor fd = has != 0
? AssetFileDescriptor.CREATOR.createFromParcel(reply) : null;
return fd;
} finally {
data.recycle();
reply.recycle();
}
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
* @author paulburke
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
if (DEBUG)
DatabaseUtils.dumpCursor(cursor);
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
@Override
public Uri uncanonicalize(String callingPkg, Uri url) throws RemoteException {
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
try {
data.writeInterfaceToken(IContentProvider.descriptor);
data.writeString(callingPkg);
url.writeToParcel(data, 0);
mRemote.transact(IContentProvider.UNCANONICALIZE_TRANSACTION, data, reply, 0);
DatabaseUtils.readExceptionFromParcel(reply);
Uri out = Uri.CREATOR.createFromParcel(reply);
return out;
} finally {
data.recycle();
reply.recycle();
}
}
@Override
public boolean refresh(String callingPkg, Uri url, Bundle args, ICancellationSignal signal)
throws RemoteException {
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
try {
data.writeInterfaceToken(IContentProvider.descriptor);
data.writeString(callingPkg);
url.writeToParcel(data, 0);
data.writeBundle(args);
data.writeStrongBinder(signal != null ? signal.asBinder() : null);
mRemote.transact(IContentProvider.REFRESH_TRANSACTION, data, reply, 0);
DatabaseUtils.readExceptionFromParcel(reply);
int success = reply.readInt();
return (success == 0);
} finally {
data.recycle();
reply.recycle();
}
}
public static void addFilterKeyword(int type, Collection<String> words) {
DatabaseUtils.InsertHelper ih = new DatabaseUtils.InsertHelper(getWsd(), FilterTable.TABLE_NAME);
final int nameColumn = ih.getColumnIndex(FilterTable.NAME);
final int activeColumn = ih.getColumnIndex(FilterTable.ACTIVE);
final int typeColumn = ih.getColumnIndex(FilterTable.TYPE);
try {
getWsd().beginTransaction();
for (String word : words) {
ih.prepareForInsert();
ih.bind(nameColumn, word);
ih.bind(activeColumn, true);
ih.bind(typeColumn, type);
ih.execute();
}
getWsd().setTransactionSuccessful();
} catch (SQLException e) {
} finally {
getWsd().endTransaction();
ih.close();
}
}
private static void dumpTable(String name,FileWriter sb) throws IOException{
String query="SELECT * FROM "+ name;
Cursor c=db.rawQuery(query,null);
sb.write("DUMPING: ");
sb.write(name);
sb.write(" count: ");
sb.write(""+c.getCount());
sb.write(": ");
if(c.moveToFirst()){
do{
sb.write(DatabaseUtils.dumpCurrentRowToString(c));
}while(c.moveToNext());
}
c.close();
sb.append("END DUMPING\n");
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
* @author paulburke
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
if (DEBUG)
DatabaseUtils.dumpCursor(cursor);
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
StringBuilder buf = new StringBuilder();
if (mSearchString != null) {
buf.append('(');
buf.append(Imps.Contacts.NICKNAME);
buf.append(" LIKE ");
DatabaseUtils.appendValueToSql(buf, "%" + mSearchString + "%");
buf.append(" OR ");
buf.append(Imps.Contacts.USERNAME);
buf.append(" LIKE ");
DatabaseUtils.appendValueToSql(buf, "%" + mSearchString + "%");
buf.append(')');
buf.append(" AND ");
}
buf.append(Imps.Contacts.TYPE).append('=').append(mType);
// buf.append(" ) GROUP BY(" + Imps.Contacts.USERNAME);
CursorLoader loader = new CursorLoader(getActivity(), mUri, ContactListItem.CONTACT_PROJECTION,
buf == null ? null : buf.toString(), null, Imps.Contacts.SUB_AND_ALPHA_SORT_ORDER);
return loader;
}
/**
* Prepare the where command and adds the global settings
* @param where The where command
* @return The new where command
*/
private String prepareWhere(String where) {
// Ignore non-PlayMusic tracks
where = combineWhere(where, "LocalCopyType != 300");
// Loads only offline tracks
if (mOfflineOnly)
where = combineWhere(where, "LocalCopyPath IS NOT NULL");
// Search only items which contains the key
if (!TextUtils.isEmpty(mSearchKey)) {
String searchKey = DatabaseUtils.sqlEscapeString("%" + mSearchKey + "%");
where = combineWhere(where, "(" + COLUMN_ARTIST + " LIKE " + searchKey + ")");
}
return where;
}
private String sqliteEscape(String keyWord) {
return DatabaseUtils.sqlEscapeString(keyWord);
// if ("".equals(keyWord) || keyWord == null) {
// return keyWord;
// }
// return keyWord
// .replace("'", "''")
// .replace("/", "//")
// .replace("[", "/[")
// .replace("]", "/]")
// .replace("%", "/%")
// .replace("&", "/&")
// .replace("_", "/_")
// .replace("(", "/(")
// .replace(")", "/)")
// ;
}
@VisibleForTesting
/* package */ static boolean tableExists(SQLiteDatabase readableDatabase, String tableName) {
long count =
DatabaseUtils.queryNumEntries(
readableDatabase, "sqlite_master", "tbl_name = ?", new String[] {tableName});
return count > 0;
}
long findAccountLastAuthenticatedTime(Account account) {
SQLiteDatabase db = mDeDatabase.getReadableDatabase();
return DatabaseUtils.longForQuery(db,
"SELECT " + AccountsDb.ACCOUNTS_LAST_AUTHENTICATE_TIME_EPOCH_MILLIS
+ " FROM " + TABLE_ACCOUNTS + " WHERE " + ACCOUNTS_NAME + "=? AND "
+ ACCOUNTS_TYPE + "=?",
new String[] {account.name, account.type});
}
/**
* @return number of albums from Bundle
*/
public String getNumSongs() {
String[] projection = {
BaseColumns._ID, ArtistColumns.ARTIST, ArtistColumns.NUMBER_OF_TRACKS
};
Uri uri = Audio.Artists.EXTERNAL_CONTENT_URI;
Long id = ApolloUtils.getArtistId(getArtist(), ARTIST_ID, this);
Cursor cursor = null;
try{
cursor = this.getContentResolver().query(uri, projection, BaseColumns._ID+ "=" + DatabaseUtils.sqlEscapeString(String.valueOf(id)), null, null);
}
catch(Exception e){
e.printStackTrace();
}
if(cursor == null)
return String.valueOf(0);
int mArtistNumAlbumsIndex = cursor.getColumnIndexOrThrow(ArtistColumns.NUMBER_OF_TRACKS);
if(cursor.getCount()>0){
cursor.moveToFirst();
String numAlbums = cursor.getString(mArtistNumAlbumsIndex);
cursor.close();
if(numAlbums != null){
return numAlbums;
}
}
return String.valueOf(0);
}
public long countExpireOldMessages(long timestamp) {
long start = SystemClock.elapsedRealtime();
final String[] args = {String.valueOf(timestamp)};
SQLiteDatabase db = this.getReadableDatabase();
db.beginTransaction();
long num = DatabaseUtils.queryNumEntries(db, Message.TABLENAME, "timeSent<?", args);
db.setTransactionSuccessful();
db.endTransaction();
Log.d(Config.LOGTAG, "found " + num + " expired messages in " + (SystemClock.elapsedRealtime() - start) + "ms");
return num;
}
/**
* Sets the maximum size the database will grow to. The maximum size cannot
* be set below the current size.
*
* @param numBytes the maximum database size, in bytes
* @return the new maximum database size
*/
public long setMaximumSize(long numBytes) {
long pageSize = getPageSize();
long numPages = numBytes / pageSize;
// If numBytes isn't a multiple of pageSize, bump up a page
if ((numBytes % pageSize) != 0) {
numPages++;
}
long newPageCount = DatabaseUtils.longForQuery(this, "PRAGMA max_page_count = " + numPages,
null);
return newPageCount * pageSize;
}
private PreparedStatement acquirePreparedStatement(String sql) {
PreparedStatement statement = mPreparedStatementCache.get(sql);
boolean skipCache = false;
if (statement != null) {
if (!statement.mInUse) {
return statement;
}
// The statement is already in the cache but is in use (this statement appears
// to be not only re-entrant but recursive!). So prepare a new copy of the
// statement but do not cache it.
skipCache = true;
}
final long statementPtr = nativePrepareStatement(mConnectionPtr, sql);
try {
final int numParameters = nativeGetParameterCount(mConnectionPtr, statementPtr);
final int type = DatabaseUtils.getSqlStatementType(sql);
final boolean readOnly = nativeIsReadOnly(mConnectionPtr, statementPtr);
statement = obtainPreparedStatement(sql, statementPtr, numParameters, type, readOnly);
if (!skipCache && isCacheable(type)) {
mPreparedStatementCache.put(sql, statement);
statement.mInCache = true;
}
} catch (RuntimeException ex) {
// Finalize the statement if an exception occurred and we did not add
// it to the cache. If it is already in the cache, then leave it there.
if (statement == null || !statement.mInCache) {
nativeFinalizeStatement(mConnectionPtr, statementPtr);
}
throw ex;
}
statement.mInUse = true;
return statement;
}
@Override
public void onCreate(@NonNull SQLiteDatabase db) {
String CREATE_BOOKMARK_TABLE = "CREATE TABLE " +
DatabaseUtils.sqlEscapeString(TABLE_BOOKMARK) + '(' +
DatabaseUtils.sqlEscapeString(KEY_ID) + " INTEGER PRIMARY KEY," +
DatabaseUtils.sqlEscapeString(KEY_URL) + " TEXT," +
DatabaseUtils.sqlEscapeString(KEY_TITLE) + " TEXT," +
DatabaseUtils.sqlEscapeString(KEY_FOLDER) + " TEXT," +
DatabaseUtils.sqlEscapeString(KEY_POSITION) + " INTEGER" + ')';
db.execSQL(CREATE_BOOKMARK_TABLE);
}
/**
* Creates a SQL {@code WHERE} clause for an issuer.
*
* @param issuer may be {@code null}
* @return an appropriate SQLite {@code WHERE} clause for this {@code issuer}
*/
private static String whereClauseForIssuer(String issuer) {
if (issuer != null) {
return ISSUER_COLUMN + " = " + DatabaseUtils.sqlEscapeString(issuer);
}
return ISSUER_COLUMN + " IS NULL";
}