Class SQLiteDatabase
-
- All Implemented Interfaces:
-
androidx.sqlite.db.SupportSQLiteDatabase,java.io.Closeable,java.lang.AutoCloseable
public final class SQLiteDatabase extends SQLiteClosable implements SupportSQLiteDatabase
Exposes methods to manage a SQLite database.
SQLiteDatabase has methods to create, delete, execute SQL commands, and perform other common database management tasks.
See the Notepad sample application in the SDK for an example of creating and managing a database.
Database names must be unique within an application, not across all applications.
In addition to SQLite's default
BINARYcollator, Android supplies two more,LOCALIZED, which changes with the system's current locale, andUNICODE, which is the Unicode Collation Algorithm and not tailored to the current locale.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description public interfaceSQLiteDatabase.CursorFactoryUsed to allow returning sub-classes of Cursor when calling query.
public interfaceSQLiteDatabase.CustomFunctionA callback interface for a custom sqlite3 function. This can be used to create a function that can be called from sqlite3 database triggers.
-
Field Summary
Fields Modifier and Type Field Description public final static intCONFLICT_ROLLBACKpublic final static intCONFLICT_ABORTpublic final static intCONFLICT_FAILpublic final static intCONFLICT_IGNOREpublic final static intCONFLICT_REPLACEpublic final static intCONFLICT_NONEpublic final static intSQLITE_MAX_LIKE_PATTERN_LENGTHpublic final static intOPEN_READWRITEpublic final static intOPEN_READONLYpublic final static intNO_LOCALIZED_COLLATORSpublic final static intCREATE_IF_NECESSARYpublic final static intENABLE_WRITE_AHEAD_LOGGINGpublic final static intMAX_SQL_CACHE_SIZE
-
Method Summary
Modifier and Type Method Description static intreleaseMemory()Attempts to release memory that SQLite holds but does not require to operate properly. voidsetLockingEnabled(boolean lockingEnabled)Control whether or not the SQLiteDatabase is made thread-safe by using locks around critical sections. voidbeginTransactionReadOnly()voidbeginTransactionWithListenerReadOnly(SQLiteTransactionListener transactionListener)voidbeginTransaction()Begins a transaction in EXCLUSIVE mode. voidbeginTransactionNonExclusive()Begins a transaction in IMMEDIATE mode. voidbeginTransactionWithListener(SQLiteTransactionListener transactionListener)voidbeginTransactionWithListenerNonExclusive(SQLiteTransactionListener transactionListener)voidbeginTransactionWithListener(SQLiteTransactionListener transactionListener)Begins a transaction in EXCLUSIVE mode. voidbeginTransactionWithListenerNonExclusive(SQLiteTransactionListener transactionListener)Begins a transaction in IMMEDIATE mode. voidendTransaction()End a transaction. voidsetTransactionSuccessful()Marks the current transaction as successful. booleaninTransaction()Returns true if the current thread has a transaction pending. booleanisDbLockedByCurrentThread()Returns true if the current thread is holding an active connection to the database. booleanisDbLockedByOtherThreads()Always returns false. booleanyieldIfContended()Temporarily end the transaction to let other threads run. booleanyieldIfContendedSafely()Temporarily end the transaction to let other threads run. booleanyieldIfContendedSafely(long sleepAfterYieldDelay)Temporarily end the transaction to let other threads run. Map<String, String>getSyncedTables()Deprecated. static SQLiteDatabaseopenDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)Open the database according to the flags OPEN_READWRITEOPEN_READONLYCREATE_IF_NECESSARY and/or NO_LOCALIZED_COLLATORS. static SQLiteDatabaseopenDatabase(String path, String password, SQLiteDatabase.CursorFactory factory, int flags, SQLiteDatabaseHook databaseHook)Open the database according to the flags OPEN_READWRITEOPEN_READONLYCREATE_IF_NECESSARY and/or NO_LOCALIZED_COLLATORS. static SQLiteDatabaseopenDatabase(String path, Array<byte> password, SQLiteDatabase.CursorFactory factory, int flags, SQLiteDatabaseHook databaseHook)Open the database according to the flags OPEN_READWRITEOPEN_READONLYCREATE_IF_NECESSARY and/or NO_LOCALIZED_COLLATORS. static SQLiteDatabaseopenDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags, DatabaseErrorHandler errorHandler)Open the database according to the flags OPEN_READWRITEOPEN_READONLYCREATE_IF_NECESSARY and/or NO_LOCALIZED_COLLATORS. static SQLiteDatabaseopenDatabase(String path, String password, SQLiteDatabase.CursorFactory factory, int flags, DatabaseErrorHandler errorHandler, SQLiteDatabaseHook databaseHook)Open the database according to the flags OPEN_READWRITEOPEN_READONLYCREATE_IF_NECESSARY and/or NO_LOCALIZED_COLLATORS. static SQLiteDatabaseopenDatabase(String path, Array<byte> password, SQLiteDatabase.CursorFactory factory, int flags, DatabaseErrorHandler errorHandler, SQLiteDatabaseHook databaseHook)Open the database according to the flags OPEN_READWRITEOPEN_READONLYCREATE_IF_NECESSARY and/or NO_LOCALIZED_COLLATORS. static SQLiteDatabaseopenOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)Equivalent to openDatabase(file.getPath(), factory, CREATE_IF_NECESSARY). static SQLiteDatabaseopenOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY). static SQLiteDatabaseopenOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler)Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY, errorHandler). static SQLiteDatabaseopenOrCreateDatabase(File file, String password, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler)Equivalent to openDatabase(file.getAbsolutePath(), password, factory, CREATE_IF_NECESSARY, errorHandler, null). static SQLiteDatabaseopenOrCreateDatabase(File file, Array<byte> password, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler)Equivalent to openDatabase(file.getAbsolutePath(), password, factory, CREATE_IF_NECESSARY, errorHandler, null). static SQLiteDatabaseopenOrCreateDatabase(String path, String password, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler)Equivalent to openDatabase(path, password, factory, CREATE_IF_NECESSARY, errorHandler, null). static SQLiteDatabaseopenOrCreateDatabase(String path, Array<byte> password, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler)Equivalent to openDatabase(path, password, factory, CREATE_IF_NECESSARY, errorHandler, null). static SQLiteDatabaseopenOrCreateDatabase(File file, String password, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler, SQLiteDatabaseHook databaseHook)Equivalent to openDatabase(file.getAbsolutePath(), password, factory, CREATE_IF_NECESSARY, errorHandler, databaseHook). static SQLiteDatabaseopenOrCreateDatabase(File file, Array<byte> password, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler, SQLiteDatabaseHook databaseHook)Equivalent to openDatabase(file.getAbsolutePath(), password, factory, CREATE_IF_NECESSARY, errorHandler, databaseHook). static SQLiteDatabaseopenOrCreateDatabase(String path, String password, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler, SQLiteDatabaseHook databaseHook)Equivalent to openDatabase(path, password, factory, CREATE_IF_NECESSARY, errorHandler, databaseHook). static SQLiteDatabaseopenOrCreateDatabase(String path, Array<byte> password, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler, SQLiteDatabaseHook databaseHook)Equivalent to openDatabase(path, password, factory, CREATE_IF_NECESSARY, errorHandler, databaseHook). static booleandeleteDatabase(File file)Deletes a database including its journal file and other auxiliary files that may have been created by the database engine. voidreopenReadWrite()Reopens the database in read-write mode. static SQLiteDatabasecreate(SQLiteDatabase.CursorFactory factory)Create a memory backed SQLite database. voidaddCustomFunction(String name, int numArgs, SQLiteDatabase.CustomFunction function)Registers a CustomFunction callback as a function that can be called from SQLite database triggers. intgetVersion()Gets the database version. voidsetVersion(int version)Sets the database version. longgetMaximumSize()Returns the maximum size the database may grow to. longsetMaximumSize(long numBytes)Sets the maximum size the database will grow to. longgetPageSize()Returns the current database page size, in bytes. voidsetPageSize(long numBytes)Sets the database page size. Cursorquery(String query)Cursorquery(String query, Array<Object> bindArgs)Cursorquery(SupportSQLiteQuery query)Cursorquery(SupportSQLiteQuery query, CancellationSignal cancellationSignal)longinsert(String table, int conflictAlgorithm, ContentValues values)intdelete(String table, String whereClause, Array<Object> whereArgs)intupdate(String table, int conflictAlgorithm, ContentValues values, String whereClause, Array<Object> whereArgs)voidmarkTableSyncable(String table, String deletedTable)Mark this table as syncable. voidmarkTableSyncable(String table, String foreignKey, String updateTable)Mark this table as syncable, with the _sync_dirty residing in another table. static StringfindEditTable(String tables)Finds the name of the first table, which is editable. SQLiteStatementcompileStatement(String sql)Compiles an SQL statement into a reusable pre-compiled statement object. Cursorquery(boolean distinct, String table, Array<String> columns, String selection, Array<String> selectionArgs, String groupBy, String having, String orderBy, String limit)Query the given URL, returning a Cursor over the result set. Cursorquery(boolean distinct, String table, Array<String> columns, String selection, Array<String> selectionArgs, String groupBy, String having, String orderBy, String limit, CancellationSignal cancellationSignal)Query the given URL, returning a Cursor over the result set. CursorqueryWithFactory(SQLiteDatabase.CursorFactory cursorFactory, boolean distinct, String table, Array<String> columns, String selection, Array<String> selectionArgs, String groupBy, String having, String orderBy, String limit)Query the given URL, returning a Cursor over the result set. CursorqueryWithFactory(SQLiteDatabase.CursorFactory cursorFactory, boolean distinct, String table, Array<String> columns, String selection, Array<String> selectionArgs, String groupBy, String having, String orderBy, String limit, CancellationSignal cancellationSignal)Query the given URL, returning a Cursor over the result set. Cursorquery(String table, Array<String> columns, String selection, Array<String> selectionArgs, String groupBy, String having, String orderBy)Query the given table, returning a Cursor over the result set. Cursorquery(String table, Array<String> columns, String selection, Array<String> selectionArgs, String groupBy, String having, String orderBy, String limit)Query the given table, returning a Cursor over the result set. CursorrawQuery(String sql, Array<String> selectionArgs)Runs the provided SQL and returns a Cursor over the result set. CursorrawQuery(String sql, Array<Object> bindingArgs)Runs the provided SQL and returns a Cursor over the result set. CursorrawQuery(String sql, Array<String> selectionArgs, CancellationSignal cancellationSignal)Runs the provided SQL and returns a Cursor over the result set. CursorrawQueryWithFactory(SQLiteDatabase.CursorFactory cursorFactory, String sql, Array<String> selectionArgs, String editTable)Runs the provided SQL and returns a cursor over the result set. CursorrawQueryWithFactory(SQLiteDatabase.CursorFactory cursorFactory, String sql, Array<String> selectionArgs, String editTable, CancellationSignal cancellationSignal)Runs the provided SQL and returns a cursor over the result set. longinsert(String table, String nullColumnHack, ContentValues values)Convenience method for inserting a row into the database. longinsertOrThrow(String table, String nullColumnHack, ContentValues values)Convenience method for inserting a row into the database. longreplace(String table, String nullColumnHack, ContentValues initialValues)Convenience method for replacing a row in the database. longreplaceOrThrow(String table, String nullColumnHack, ContentValues initialValues)Convenience method for replacing a row in the database. longinsertWithOnConflict(String table, String nullColumnHack, ContentValues initialValues, int conflictAlgorithm)General method for inserting a row into the database. intdelete(String table, String whereClause, Array<String> whereArgs)Convenience method for deleting rows in the database. intupdate(String table, ContentValues values, String whereClause, Array<String> whereArgs)Convenience method for updating rows in the database. intupdateWithOnConflict(String table, ContentValues values, String whereClause, Array<String> whereArgs, int conflictAlgorithm)Convenience method for updating rows in the database. voidexecSQL(String sql)Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data. voidexecSQL(String sql, Array<Object> bindArgs)Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE. voidrawExecSQL(String sql, Array<Object> bindArgs)Executes a statement that returns a count of the number of rows that were changed. voidvalidateSql(String sql, CancellationSignal cancellationSignal)Verifies that a SQL SELECT statement is valid by compiling it. booleanisReadOnly()Returns true if the database is opened as read only. booleanisInMemoryDatabase()Returns true if the database is in-memory db. booleanisOpen()Returns true if the database is currently open. booleanneedUpgrade(int newVersion)Returns true if the new version code is greater than the current database version. final StringgetPath()Gets the path to the database file. voidsetLocale(Locale locale)Sets the locale for this database. voidsetMaxSqlCacheSize(int cacheSize)Sets the maximum size of the prepared-statement cache for this database. voidsetForeignKeyConstraintsEnabled(boolean enable)Sets whether foreign key constraints are enabled for the database. booleanenableWriteAheadLogging()This method enables parallel execution of queries from multiple threads on the same database. voiddisableWriteAheadLogging()This method disables the features enabled by enableWriteAheadLogging. booleanisWriteAheadLoggingEnabled()Returns true if write-ahead logging has been enabled for this database. List<Pair<String, String>>getAttachedDbs()Returns list of full pathnames of all attached databases including the main database by executing 'pragma database_list' on the database. booleanisDatabaseIntegrityOk()Runs 'pragma integrity_check' on the given database (and all the attached databases) and returns true if the given database (and all its attached databases) pass integrity_check, false otherwise. voidchangePassword(String newPassword)voidchangePassword(Array<byte> newPassword)StringtoString()static booleanhasCodec()voidenableLocalizedCollators()-
Methods inherited from class net.zetetic.database.sqlcipher.SQLiteClosable
acquireReference, close, releaseReference, releaseReferenceFromContainer -
Methods inherited from class androidx.sqlite.db.SupportSQLiteDatabase
execPerConnectionSQL, isExecPerConnectionSQLSupported -
Methods inherited from class java.io.Closeable
close -
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
-
-
Method Detail
-
releaseMemory
static int releaseMemory()
Attempts to release memory that SQLite holds but does not require to operate properly. Typically this memory will come from the page cache.
- Returns:
the number of bytes actually released
-
setLockingEnabled
@Deprecated() void setLockingEnabled(boolean lockingEnabled)
Control whether or not the SQLiteDatabase is made thread-safe by using locks around critical sections. This is pretty expensive, so if you know that your DB will only be used by a single thread then you should set this to false. The default is true.
- Parameters:
lockingEnabled- set to true to enable locks, false otherwise
-
beginTransactionReadOnly
void beginTransactionReadOnly()
-
beginTransactionWithListenerReadOnly
void beginTransactionWithListenerReadOnly(SQLiteTransactionListener transactionListener)
-
beginTransaction
void beginTransaction()
Begins a transaction in EXCLUSIVE mode.
Transactions can be nested. When the outer transaction is ended all of the work done in that transaction and all of the nested transactions will be committed or rolled back. The changes will be rolled back if any transaction is ended without being marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
Here is the standard idiom for transactions:
db.beginTransaction(); try { ... db.setTransactionSuccessful(); } finally { db.endTransaction(); }
-
beginTransactionNonExclusive
void beginTransactionNonExclusive()
Begins a transaction in IMMEDIATE mode. Transactions can be nested. When the outer transaction is ended all of the work done in that transaction and all of the nested transactions will be committed or rolled back. The changes will be rolled back if any transaction is ended without being marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
Here is the standard idiom for transactions:
db.beginTransactionNonExclusive(); try { ... db.setTransactionSuccessful(); } finally { db.endTransaction(); }
-
beginTransactionWithListener
void beginTransactionWithListener(SQLiteTransactionListener transactionListener)
-
beginTransactionWithListenerNonExclusive
void beginTransactionWithListenerNonExclusive(SQLiteTransactionListener transactionListener)
-
beginTransactionWithListener
void beginTransactionWithListener(SQLiteTransactionListener transactionListener)
Begins a transaction in EXCLUSIVE mode.
Transactions can be nested. When the outer transaction is ended all of the work done in that transaction and all of the nested transactions will be committed or rolled back. The changes will be rolled back if any transaction is ended without being marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
Here is the standard idiom for transactions:
db.beginTransactionWithListener(listener); try { ... db.setTransactionSuccessful(); } finally { db.endTransaction(); }- Parameters:
transactionListener- listener that should be notified when the transaction begins, commits, or is rolled back, either explicitly or by a call to yieldIfContendedSafely.
-
beginTransactionWithListenerNonExclusive
void beginTransactionWithListenerNonExclusive(SQLiteTransactionListener transactionListener)
Begins a transaction in IMMEDIATE mode. Transactions can be nested. When the outer transaction is ended all of the work done in that transaction and all of the nested transactions will be committed or rolled back. The changes will be rolled back if any transaction is ended without being marked as clean (by calling setTransactionSuccessful). Otherwise they will be committed.
Here is the standard idiom for transactions:
db.beginTransactionWithListenerNonExclusive(listener); try { ... db.setTransactionSuccessful(); } finally { db.endTransaction(); }- Parameters:
transactionListener- listener that should be notified when the transaction begins, commits, or is rolled back, either explicitly or by a call to yieldIfContendedSafely.
-
endTransaction
void endTransaction()
End a transaction. See beginTransaction for notes about how to use this and when transactions are committed and rolled back.
-
setTransactionSuccessful
void setTransactionSuccessful()
Marks the current transaction as successful. Do not do any more database work between calling this and calling endTransaction. Do as little non-database work as possible in that situation too. If any errors are encountered between this and endTransaction the transaction will still be committed.
-
inTransaction
boolean inTransaction()
Returns true if the current thread has a transaction pending.
- Returns:
True if the current thread is in a transaction.
-
isDbLockedByCurrentThread
boolean isDbLockedByCurrentThread()
Returns true if the current thread is holding an active connection to the database.
The name of this method comes from a time when having an active connection to the database meant that the thread was holding an actual lock on the database. Nowadays, there is no longer a true "database lock" although threads may block if they cannot acquire a database connection to perform a particular operation.
- Returns:
True if the current thread is holding an active connection to the database.
-
isDbLockedByOtherThreads
@Deprecated() boolean isDbLockedByOtherThreads()
Always returns false.
There is no longer the concept of a database lock, so this method always returns false.
- Returns:
False.
-
yieldIfContended
@Deprecated() boolean yieldIfContended()
Temporarily end the transaction to let other threads run. The transaction is assumed to be successful so far. Do not call setTransactionSuccessful before calling this. When this returns a new transaction will have been created but not marked as successful.
- Returns:
true if the transaction was yielded
-
yieldIfContendedSafely
boolean yieldIfContendedSafely()
Temporarily end the transaction to let other threads run. The transaction is assumed to be successful so far. Do not call setTransactionSuccessful before calling this. When this returns a new transaction will have been created but not marked as successful. This assumes that there are no nested transactions (beginTransaction has only been called once) and will throw an exception if that is not the case.
- Returns:
true if the transaction was yielded
-
yieldIfContendedSafely
boolean yieldIfContendedSafely(long sleepAfterYieldDelay)
Temporarily end the transaction to let other threads run. The transaction is assumed to be successful so far. Do not call setTransactionSuccessful before calling this. When this returns a new transaction will have been created but not marked as successful. This assumes that there are no nested transactions (beginTransaction has only been called once) and will throw an exception if that is not the case.
- Parameters:
sleepAfterYieldDelay- if >0, sleep this long before starting a new transaction if the lock was actually yielded.- Returns:
true if the transaction was yielded
-
getSyncedTables
@Deprecated() Map<String, String> getSyncedTables()
Deprecated.
-
openDatabase
static SQLiteDatabase openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)
Open the database according to the flags OPEN_READWRITEOPEN_READONLYCREATE_IF_NECESSARY and/or NO_LOCALIZED_COLLATORS.
Sets the locale of the database to the the system's current locale. Call setLocale if you would like something else.
- Parameters:
path- to database file to open and/or createfactory- an optional factory class that is called to instantiate a cursor when query is called, or null for defaultflags- to control database access mode- Returns:
the newly opened database
-
openDatabase
static SQLiteDatabase openDatabase(String path, String password, SQLiteDatabase.CursorFactory factory, int flags, SQLiteDatabaseHook databaseHook)
Open the database according to the flags OPEN_READWRITEOPEN_READONLYCREATE_IF_NECESSARY and/or NO_LOCALIZED_COLLATORS.
Sets the locale of the database to the the system's current locale. Call setLocale if you would like something else.
- Parameters:
path- to database file to open and/or createpassword- for use with a SQLCipher databasefactory- an optional factory class that is called to instantiate a cursor when query is called, or null for defaultflags- to control database access modedatabaseHook- to invoke preKey and postKey operations with SQLCipher- Returns:
the newly opened database
-
openDatabase
static SQLiteDatabase openDatabase(String path, Array<byte> password, SQLiteDatabase.CursorFactory factory, int flags, SQLiteDatabaseHook databaseHook)
Open the database according to the flags OPEN_READWRITEOPEN_READONLYCREATE_IF_NECESSARY and/or NO_LOCALIZED_COLLATORS.
Sets the locale of the database to the the system's current locale. Call setLocale if you would like something else.
- Parameters:
path- to database file to open and/or createpassword- for use with a SQLCipher databasefactory- an optional factory class that is called to instantiate a cursor when query is called, or null for defaultflags- to control database access modedatabaseHook- to invoke preKey and postKey operations with SQLCipher- Returns:
the newly opened database
-
openDatabase
static SQLiteDatabase openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags, DatabaseErrorHandler errorHandler)
Open the database according to the flags OPEN_READWRITEOPEN_READONLYCREATE_IF_NECESSARY and/or NO_LOCALIZED_COLLATORS.
Sets the locale of the database to the the system's current locale. Call setLocale if you would like something else.
Accepts input param: a concrete instance of DatabaseErrorHandler to be used to handle corruption when sqlite reports database corruption.
- Parameters:
path- to database file to open and/or createfactory- an optional factory class that is called to instantiate a cursor when query is called, or null for defaultflags- to control database access modeerrorHandler- the DatabaseErrorHandler obj to be used to handle corruption when sqlite reports database corruption- Returns:
the newly opened database
-
openDatabase
static SQLiteDatabase openDatabase(String path, String password, SQLiteDatabase.CursorFactory factory, int flags, DatabaseErrorHandler errorHandler, SQLiteDatabaseHook databaseHook)
Open the database according to the flags OPEN_READWRITEOPEN_READONLYCREATE_IF_NECESSARY and/or NO_LOCALIZED_COLLATORS.
Sets the locale of the database to the the system's current locale. Call setLocale if you would like something else.
Accepts input param: a concrete instance of DatabaseErrorHandler to be used to handle corruption when sqlite reports database corruption.
- Parameters:
path- to database file to open and/or createpassword- for use with a SQLCipher databasefactory- an optional factory class that is called to instantiate a cursor when query is called, or null for defaultflags- to control database access modeerrorHandler- the DatabaseErrorHandler obj to be used to handle corruption when sqlite reports database corruptiondatabaseHook- to invoke preKey and postKey operations with SQLCipher- Returns:
the newly opened database
-
openDatabase
static SQLiteDatabase openDatabase(String path, Array<byte> password, SQLiteDatabase.CursorFactory factory, int flags, DatabaseErrorHandler errorHandler, SQLiteDatabaseHook databaseHook)
Open the database according to the flags OPEN_READWRITEOPEN_READONLYCREATE_IF_NECESSARY and/or NO_LOCALIZED_COLLATORS.
Sets the locale of the database to the the system's current locale. Call setLocale if you would like something else.
Accepts input param: a concrete instance of DatabaseErrorHandler to be used to handle corruption when sqlite reports database corruption.
- Parameters:
path- to database file to open and/or createpassword- for use with a SQLCipher databasefactory- an optional factory class that is called to instantiate a cursor when query is called, or null for defaultflags- to control database access modeerrorHandler- the DatabaseErrorHandler obj to be used to handle corruption when sqlite reports database corruptiondatabaseHook- to invoke preKey and postKey operations with SQLCipher- Returns:
the newly opened database
-
openOrCreateDatabase
static SQLiteDatabase openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)
Equivalent to openDatabase(file.getPath(), factory, CREATE_IF_NECESSARY).
-
openOrCreateDatabase
static SQLiteDatabase openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)
Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY).
-
openOrCreateDatabase
static SQLiteDatabase openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler)
Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY, errorHandler).
-
openOrCreateDatabase
static SQLiteDatabase openOrCreateDatabase(File file, String password, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler)
Equivalent to openDatabase(file.getAbsolutePath(), password, factory, CREATE_IF_NECESSARY, errorHandler, null).
-
openOrCreateDatabase
static SQLiteDatabase openOrCreateDatabase(File file, Array<byte> password, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler)
Equivalent to openDatabase(file.getAbsolutePath(), password, factory, CREATE_IF_NECESSARY, errorHandler, null).
-
openOrCreateDatabase
static SQLiteDatabase openOrCreateDatabase(String path, String password, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler)
Equivalent to openDatabase(path, password, factory, CREATE_IF_NECESSARY, errorHandler, null).
-
openOrCreateDatabase
static SQLiteDatabase openOrCreateDatabase(String path, Array<byte> password, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler)
Equivalent to openDatabase(path, password, factory, CREATE_IF_NECESSARY, errorHandler, null).
-
openOrCreateDatabase
static SQLiteDatabase openOrCreateDatabase(File file, String password, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler, SQLiteDatabaseHook databaseHook)
Equivalent to openDatabase(file.getAbsolutePath(), password, factory, CREATE_IF_NECESSARY, errorHandler, databaseHook).
-
openOrCreateDatabase
static SQLiteDatabase openOrCreateDatabase(File file, Array<byte> password, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler, SQLiteDatabaseHook databaseHook)
Equivalent to openDatabase(file.getAbsolutePath(), password, factory, CREATE_IF_NECESSARY, errorHandler, databaseHook).
-
openOrCreateDatabase
static SQLiteDatabase openOrCreateDatabase(String path, String password, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler, SQLiteDatabaseHook databaseHook)
Equivalent to openDatabase(path, password, factory, CREATE_IF_NECESSARY, errorHandler, databaseHook).
-
openOrCreateDatabase
static SQLiteDatabase openOrCreateDatabase(String path, Array<byte> password, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler, SQLiteDatabaseHook databaseHook)
Equivalent to openDatabase(path, password, factory, CREATE_IF_NECESSARY, errorHandler, databaseHook).
-
deleteDatabase
static boolean deleteDatabase(File file)
Deletes a database including its journal file and other auxiliary files that may have been created by the database engine.
- Parameters:
file- The database file path.- Returns:
True if the database was successfully deleted.
-
reopenReadWrite
void reopenReadWrite()
Reopens the database in read-write mode. If the database is already read-write, does nothing.
-
create
static SQLiteDatabase create(SQLiteDatabase.CursorFactory factory)
Create a memory backed SQLite database. Its contents will be destroyed when the database is closed.
Sets the locale of the database to the the system's current locale. Call setLocale if you would like something else.
- Parameters:
factory- an optional factory class that is called to instantiate a cursor when query is called- Returns:
a SQLiteDatabase object, or null if the database can't be created
-
addCustomFunction
void addCustomFunction(String name, int numArgs, SQLiteDatabase.CustomFunction function)
Registers a CustomFunction callback as a function that can be called from SQLite database triggers.
- Parameters:
name- the name of the sqlite3 functionnumArgs- the number of arguments for the functionfunction- callback to call when the function is executed
-
getVersion
int getVersion()
Gets the database version.
- Returns:
the database version
-
setVersion
void setVersion(int version)
Sets the database version.
- Parameters:
version- the new database version
-
getMaximumSize
long getMaximumSize()
Returns the maximum size the database may grow to.
- Returns:
the new maximum database size
-
setMaximumSize
long setMaximumSize(long numBytes)
Sets the maximum size the database will grow to. The maximum size cannot be set below the current size.
- Parameters:
numBytes- the maximum database size, in bytes- Returns:
the new maximum database size
-
getPageSize
long getPageSize()
Returns the current database page size, in bytes.
- Returns:
the database page size, in bytes
-
setPageSize
void setPageSize(long numBytes)
Sets the database page size. The page size must be a power of two. This method does not work if any data has been written to the database file, and must be called right after the database has been created.
- Parameters:
numBytes- the database page size, in bytes
-
query
Cursor query(SupportSQLiteQuery query)
-
query
Cursor query(SupportSQLiteQuery query, CancellationSignal cancellationSignal)
-
insert
long insert(String table, int conflictAlgorithm, ContentValues values)
-
update
int update(String table, int conflictAlgorithm, ContentValues values, String whereClause, Array<Object> whereArgs)
-
markTableSyncable
@Deprecated() void markTableSyncable(String table, String deletedTable)
Mark this table as syncable. When an update occurs in this table the _sync_dirty field will be set to ensure proper syncing operation.
- Parameters:
table- the table to mark as syncabledeletedTable- The deleted table that corresponds to the syncable table
-
markTableSyncable
@Deprecated() void markTableSyncable(String table, String foreignKey, String updateTable)
Mark this table as syncable, with the _sync_dirty residing in another table. When an update occurs in this table the _sync_dirty field of the row in updateTable with the _id in foreignKey will be set to ensure proper syncing operation.
- Parameters:
table- an update on this table will trigger a sync time removalforeignKey- this is the column in table whose value is an _id in updateTableupdateTable- this is the table that will have its _sync_dirty
-
findEditTable
static String findEditTable(String tables)
Finds the name of the first table, which is editable.
- Parameters:
tables- a list of tables- Returns:
the first table listed
-
compileStatement
SQLiteStatement compileStatement(String sql)
Compiles an SQL statement into a reusable pre-compiled statement object. The parameters are identical to execSQL. You may put ?s in the statement and fill in those values with bindString and bindLong each time you want to run the statement. Statements may not return result sets larger than 1x1.
No two threads should be using the same SQLiteStatement at the same time.
- Parameters:
sql- The raw SQL statement, may contain ?- Returns:
A pre-compiled SQLiteStatement object. Note that SQLiteStatements are not synchronized, see the documentation for more details.
-
query
Cursor query(boolean distinct, String table, Array<String> columns, String selection, Array<String> selectionArgs, String groupBy, String having, String orderBy, String limit)
Query the given URL, returning a Cursor over the result set.
- Parameters:
distinct- true if you want each row to be unique, false otherwise.table- The table name to compile the query against.columns- A list of which columns to return.selection- A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself).selectionArgs- You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection.groupBy- A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself).having- A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself).orderBy- How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself).limit- Limits the number of rows returned by the query, formatted as LIMIT clause.- Returns:
A Cursor object, which is positioned before the first entry. Note that Cursors are not synchronized, see the documentation for more details.
-
query
Cursor query(boolean distinct, String table, Array<String> columns, String selection, Array<String> selectionArgs, String groupBy, String having, String orderBy, String limit, CancellationSignal cancellationSignal)
Query the given URL, returning a Cursor over the result set.
- Parameters:
distinct- true if you want each row to be unique, false otherwise.table- The table name to compile the query against.columns- A list of which columns to return.selection- A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself).selectionArgs- You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection.groupBy- A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself).having- A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself).orderBy- How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself).limit- Limits the number of rows returned by the query, formatted as LIMIT clause.cancellationSignal- A signal to cancel the operation in progress, or null if none.- Returns:
A Cursor object, which is positioned before the first entry. Note that Cursors are not synchronized, see the documentation for more details.
-
queryWithFactory
Cursor queryWithFactory(SQLiteDatabase.CursorFactory cursorFactory, boolean distinct, String table, Array<String> columns, String selection, Array<String> selectionArgs, String groupBy, String having, String orderBy, String limit)
Query the given URL, returning a Cursor over the result set.
- Parameters:
cursorFactory- the cursor factory to use, or null for the default factorydistinct- true if you want each row to be unique, false otherwise.table- The table name to compile the query against.columns- A list of which columns to return.selection- A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself).selectionArgs- You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection.groupBy- A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself).having- A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself).orderBy- How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself).limit- Limits the number of rows returned by the query, formatted as LIMIT clause.- Returns:
A Cursor object, which is positioned before the first entry. Note that Cursors are not synchronized, see the documentation for more details.
-
queryWithFactory
Cursor queryWithFactory(SQLiteDatabase.CursorFactory cursorFactory, boolean distinct, String table, Array<String> columns, String selection, Array<String> selectionArgs, String groupBy, String having, String orderBy, String limit, CancellationSignal cancellationSignal)
Query the given URL, returning a Cursor over the result set.
- Parameters:
cursorFactory- the cursor factory to use, or null for the default factorydistinct- true if you want each row to be unique, false otherwise.table- The table name to compile the query against.columns- A list of which columns to return.selection- A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself).selectionArgs- You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection.groupBy- A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself).having- A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself).orderBy- How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself).limit- Limits the number of rows returned by the query, formatted as LIMIT clause.cancellationSignal- A signal to cancel the operation in progress, or null if none.- Returns:
A Cursor object, which is positioned before the first entry. Note that Cursors are not synchronized, see the documentation for more details.
-
query
Cursor query(String table, Array<String> columns, String selection, Array<String> selectionArgs, String groupBy, String having, String orderBy)
Query the given table, returning a Cursor over the result set.
- Parameters:
table- The table name to compile the query against.columns- A list of which columns to return.selection- A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself).selectionArgs- You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection.groupBy- A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself).having- A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself).orderBy- How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself).- Returns:
A Cursor object, which is positioned before the first entry. Note that Cursors are not synchronized, see the documentation for more details.
-
query
Cursor query(String table, Array<String> columns, String selection, Array<String> selectionArgs, String groupBy, String having, String orderBy, String limit)
Query the given table, returning a Cursor over the result set.
- Parameters:
table- The table name to compile the query against.columns- A list of which columns to return.selection- A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself).selectionArgs- You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection.groupBy- A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself).having- A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself).orderBy- How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself).limit- Limits the number of rows returned by the query, formatted as LIMIT clause.- Returns:
A Cursor object, which is positioned before the first entry. Note that Cursors are not synchronized, see the documentation for more details.
-
rawQuery
Cursor rawQuery(String sql, Array<String> selectionArgs)
Runs the provided SQL and returns a Cursor over the result set.
- Parameters:
sql- the SQL query.selectionArgs- You may include ?s in where clause in the query, which will be replaced by the values from selectionArgs.- Returns:
A Cursor object, which is positioned before the first entry. Note that Cursors are not synchronized, see the documentation for more details.
-
rawQuery
Cursor rawQuery(String sql, Array<Object> bindingArgs)
Runs the provided SQL and returns a Cursor over the result set.
- Parameters:
sql- the SQL query.bindingArgs- You may include ?s in where clause in the query, which will be replaced by the values from bindingArgs.- Returns:
A Cursor object, which is positioned before the first entry. Note that Cursors are not synchronized, see the documentation for more details.
-
rawQuery
Cursor rawQuery(String sql, Array<String> selectionArgs, CancellationSignal cancellationSignal)
Runs the provided SQL and returns a Cursor over the result set.
- Parameters:
sql- the SQL query.selectionArgs- You may include ?s in where clause in the query, which will be replaced by the values from selectionArgs.cancellationSignal- A signal to cancel the operation in progress, or null if none.- Returns:
A Cursor object, which is positioned before the first entry. Note that Cursors are not synchronized, see the documentation for more details.
-
rawQueryWithFactory
Cursor rawQueryWithFactory(SQLiteDatabase.CursorFactory cursorFactory, String sql, Array<String> selectionArgs, String editTable)
Runs the provided SQL and returns a cursor over the result set.
- Parameters:
cursorFactory- the cursor factory to use, or null for the default factorysql- the SQL query.selectionArgs- You may include ?s in where clause in the query, which will be replaced by the values from selectionArgs.editTable- the name of the first table, which is editable- Returns:
A Cursor object, which is positioned before the first entry. Note that Cursors are not synchronized, see the documentation for more details.
-
rawQueryWithFactory
Cursor rawQueryWithFactory(SQLiteDatabase.CursorFactory cursorFactory, String sql, Array<String> selectionArgs, String editTable, CancellationSignal cancellationSignal)
Runs the provided SQL and returns a cursor over the result set.
- Parameters:
cursorFactory- the cursor factory to use, or null for the default factorysql- the SQL query.selectionArgs- You may include ?s in where clause in the query, which will be replaced by the values from selectionArgs.editTable- the name of the first table, which is editablecancellationSignal- A signal to cancel the operation in progress, or null if none.- Returns:
A Cursor object, which is positioned before the first entry. Note that Cursors are not synchronized, see the documentation for more details.
-
insert
long insert(String table, String nullColumnHack, ContentValues values)
Convenience method for inserting a row into the database.
- Parameters:
table- the table to insert the row intonullColumnHack- optional; may benull.values- this map contains the initial column values for the row.- Returns:
the row ID of the newly inserted row, or -1 if an error occurred
-
insertOrThrow
long insertOrThrow(String table, String nullColumnHack, ContentValues values)
Convenience method for inserting a row into the database.
- Parameters:
table- the table to insert the row intonullColumnHack- optional; may benull.values- this map contains the initial column values for the row.- Returns:
the row ID of the newly inserted row, or -1 if an error occurred
-
replace
long replace(String table, String nullColumnHack, ContentValues initialValues)
Convenience method for replacing a row in the database. Inserts a new row if a row does not already exist.
- Parameters:
table- the table in which to replace the rownullColumnHack- optional; may benull.initialValues- this map contains the initial column values for the row.- Returns:
the row ID of the newly inserted row, or -1 if an error occurred
-
replaceOrThrow
long replaceOrThrow(String table, String nullColumnHack, ContentValues initialValues)
Convenience method for replacing a row in the database. Inserts a new row if a row does not already exist.
- Parameters:
table- the table in which to replace the rownullColumnHack- optional; may benull.initialValues- this map contains the initial column values for the row.- Returns:
the row ID of the newly inserted row, or -1 if an error occurred
-
insertWithOnConflict
long insertWithOnConflict(String table, String nullColumnHack, ContentValues initialValues, int conflictAlgorithm)
General method for inserting a row into the database.
- Parameters:
table- the table to insert the row intonullColumnHack- optional; may benull.initialValues- this map contains the initial column values for the row.conflictAlgorithm- for insert conflict resolver- Returns:
the row ID of the newly inserted row OR
-1if either the input parameterconflictAlgorithm= CONFLICT_IGNORE or an error occurred.
-
delete
int delete(String table, String whereClause, Array<String> whereArgs)
Convenience method for deleting rows in the database.
- Parameters:
table- the table to delete fromwhereClause- the optional WHERE clause to apply when deleting.whereArgs- You may include ?s in the where clause, which will be replaced by the values from whereArgs.- Returns:
the number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows and get a count pass "1" as the whereClause.
-
update
int update(String table, ContentValues values, String whereClause, Array<String> whereArgs)
Convenience method for updating rows in the database.
- Parameters:
table- the table to update invalues- a map from column names to new column values.whereClause- the optional WHERE clause to apply when updating.whereArgs- You may include ?s in the where clause, which will be replaced by the values from whereArgs.- Returns:
the number of rows affected
-
updateWithOnConflict
int updateWithOnConflict(String table, ContentValues values, String whereClause, Array<String> whereArgs, int conflictAlgorithm)
Convenience method for updating rows in the database.
- Parameters:
table- the table to update invalues- a map from column names to new column values.whereClause- the optional WHERE clause to apply when updating.whereArgs- You may include ?s in the where clause, which will be replaced by the values from whereArgs.conflictAlgorithm- for update conflict resolver- Returns:
the number of rows affected
-
execSQL
void execSQL(String sql)
Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.
It has no means to return any data (such as the number of affected rows). Instead, you're encouraged to use insert, update, et al, when possible.
When using enableWriteAheadLogging, journal_mode is automatically managed by this class. So, do not set journal_mode using "PRAGMA journal_mode'" statement if your app is using
- Parameters:
sql- the SQL statement to be executed.
-
execSQL
void execSQL(String sql, Array<Object> bindArgs)
Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.
For INSERT statements, use any of the following instead.
For UPDATE statements, use any of the following instead.
For DELETE statements, use any of the following instead.
For example, the following are good candidates for using this method:
- ALTER TABLE
- CREATE or DROP table / trigger / view / index / virtual table
- REINDEX
- RELEASE
- SAVEPOINT
- PRAGMA that returns no data
When using enableWriteAheadLogging, journal_mode is automatically managed by this class. So, do not set journal_mode using "PRAGMA journal_mode'" statement if your app is using
- Parameters:
sql- the SQL statement to be executed.bindArgs- only byte[], String, Long and Double are supported in bindArgs.
-
rawExecSQL
void rawExecSQL(String sql, Array<Object> bindArgs)
Executes a statement that returns a count of the number of rows that were changed. No transaction state checking is performed.
- Parameters:
sql- The SQL statement to execute.bindArgs- The arguments to bind.- Returns:
The number of rows that were changed.
-
validateSql
void validateSql(String sql, CancellationSignal cancellationSignal)
Verifies that a SQL SELECT statement is valid by compiling it. If the SQL statement is not valid, this method will throw a SQLiteException.
- Parameters:
sql- SQL to be validatedcancellationSignal- A signal to cancel the operation in progress, or null if none.
-
isReadOnly
boolean isReadOnly()
Returns true if the database is opened as read only.
- Returns:
True if database is opened as read only.
-
isInMemoryDatabase
boolean isInMemoryDatabase()
Returns true if the database is in-memory db.
- Returns:
True if the database is in-memory.
-
isOpen
boolean isOpen()
Returns true if the database is currently open.
- Returns:
True if the database is currently open (has not been closed).
-
needUpgrade
boolean needUpgrade(int newVersion)
Returns true if the new version code is greater than the current database version.
- Parameters:
newVersion- The new version code.- Returns:
True if the new version code is greater than the current database version.
-
getPath
final String getPath()
Gets the path to the database file.
- Returns:
The path to the database file.
-
setLocale
void setLocale(Locale locale)
Sets the locale for this database. Does nothing if this database has the NO_LOCALIZED_COLLATORS flag set or was opened read only.
- Parameters:
locale- The new locale.
-
setMaxSqlCacheSize
void setMaxSqlCacheSize(int cacheSize)
Sets the maximum size of the prepared-statement cache for this database. (size of the cache = number of compiled-sql-statements stored in the cache).
Maximum cache size can ONLY be increased from its current size (default = 10). If this method is called with smaller size than the current maximum value, then IllegalStateException is thrown.
This method is thread-safe.
- Parameters:
cacheSize- the size of the cache.
-
setForeignKeyConstraintsEnabled
void setForeignKeyConstraintsEnabled(boolean enable)
Sets whether foreign key constraints are enabled for the database.
By default, foreign key constraints are not enforced by the database. This method allows an application to enable foreign key constraints. It must be called each time the database is opened to ensure that foreign key constraints are enabled for the session.
A good time to call this method is right after calling openOrCreateDatabase or in the onConfigure callback.
When foreign key constraints are disabled, the database does not check whether changes to the database will violate foreign key constraints. Likewise, when foreign key constraints are disabled, the database will not execute cascade delete or update triggers. As a result, it is possible for the database state to become inconsistent. To perform a database integrity check, call isDatabaseIntegrityOk.
This method must not be called while a transaction is in progress.
See also SQLite Foreign Key Constraints for more details about foreign key constraint support.
- Parameters:
enable- True to enable foreign key constraints, false to disable them.
-
enableWriteAheadLogging
boolean enableWriteAheadLogging()
This method enables parallel execution of queries from multiple threads on the same database. It does this by opening multiple connections to the database and using a different database connection for each query. The database journal mode is also changed to enable writes to proceed concurrently with reads.
When write-ahead logging is not enabled (the default), it is not possible for reads and writes to occur on the database at the same time. Before modifying the database, the writer implicitly acquires an exclusive lock on the database which prevents readers from accessing the database until the write is completed.
In contrast, when write-ahead logging is enabled (by calling this method), write operations occur in a separate log file which allows reads to proceed concurrently. While a write is in progress, readers on other threads will perceive the state of the database as it was before the write began. When the write completes, readers on other threads will then perceive the new state of the database.
It is a good idea to enable write-ahead logging whenever a database will be concurrently accessed and modified by multiple threads at the same time. However, write-ahead logging uses significantly more memory than ordinary journaling because there are multiple connections to the same database. So if a database will only be used by a single thread, or if optimizing concurrency is not very important, then write-ahead logging should be disabled.
After calling this method, execution of queries in parallel is enabled as long as the database remains open. To disable execution of queries in parallel, either call disableWriteAheadLogging or close the database and reopen it.
The maximum number of connections used to execute queries in parallel is dependent upon the device memory and possibly other properties.
If a query is part of a transaction, then it is executed on the same database handle the transaction was begun.
Writers should use beginTransactionNonExclusive or beginTransactionWithListenerNonExclusive to start a transaction. Non-exclusive mode allows database file to be in readable by other threads executing queries.
If the database has any attached databases, then execution of queries in parallel is NOT possible. Likewise, write-ahead logging is not supported for read-only databases or memory databases. In such cases, enableWriteAheadLogging returns false.
The best way to enable write-ahead logging is to pass the ENABLE_WRITE_AHEAD_LOGGING flag to openDatabase. This is more efficient than calling enableWriteAheadLogging.
SQLiteDatabase db = SQLiteDatabase.openDatabase("db_filename", cursorFactory, SQLiteDatabase.CREATE_IF_NECESSARY | SQLiteDatabase.ENABLE_WRITE_AHEAD_LOGGING, myDatabaseErrorHandler); db.enableWriteAheadLogging();Another way to enable write-ahead logging is to call enableWriteAheadLogging after opening the database.
SQLiteDatabase db = SQLiteDatabase.openDatabase("db_filename", cursorFactory, SQLiteDatabase.CREATE_IF_NECESSARY, myDatabaseErrorHandler); db.enableWriteAheadLogging();See also SQLite Write-Ahead Logging for more details about how write-ahead logging works.
- Returns:
True if write-ahead logging is enabled.
-
disableWriteAheadLogging
void disableWriteAheadLogging()
This method disables the features enabled by enableWriteAheadLogging.
-
isWriteAheadLoggingEnabled
boolean isWriteAheadLoggingEnabled()
Returns true if write-ahead logging has been enabled for this database.
- Returns:
True if write-ahead logging has been enabled for this database.
-
getAttachedDbs
List<Pair<String, String>> getAttachedDbs()
Returns list of full pathnames of all attached databases including the main database by executing 'pragma database_list' on the database.
- Returns:
ArrayList of pairs of (database name, database file path) or null if the database is not open.
-
isDatabaseIntegrityOk
boolean isDatabaseIntegrityOk()
Runs 'pragma integrity_check' on the given database (and all the attached databases) and returns true if the given database (and all its attached databases) pass integrity_check, false otherwise.
If the result is false, then this method logs the errors reported by the integrity_check command execution.
Note that 'pragma integrity_check' on a database can take a long time.
- Returns:
true if the given database (and all its attached databases) pass integrity_check, false otherwise.
-
changePassword
void changePassword(String newPassword)
-
changePassword
void changePassword(Array<byte> newPassword)
-
hasCodec
static boolean hasCodec()
-
enableLocalizedCollators
void enableLocalizedCollators()
-
-
-
-