public final class SQLiteDatabase extends SQLiteClosable
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 BINARY
collator, Android supplies
two more, LOCALIZED
, which changes with the system's current locale,
and UNICODE
, which is the Unicode Collation Algorithm and not tailored
to the current locale.
Modifier and Type | Class and Description |
---|---|
static interface |
SQLiteDatabase.CursorFactory
Used to allow returning sub-classes of
Cursor when calling query. |
static interface |
SQLiteDatabase.CustomFunction
A callback interface for a custom sqlite3 function.
|
Modifier and Type | Field and Description |
---|---|
static int |
CONFLICT_ABORT
When a constraint violation occurs,no ROLLBACK is executed
so changes from prior commands within the same transaction
are preserved.
|
static int |
CONFLICT_FAIL
When a constraint violation occurs, the command aborts with a return
code SQLITE_CONSTRAINT.
|
static int |
CONFLICT_IGNORE
When a constraint violation occurs, the one row that contains
the constraint violation is not inserted or changed.
|
static int |
CONFLICT_NONE
Use the following when no conflict action is specified.
|
static int |
CONFLICT_REPLACE
When a UNIQUE constraint violation occurs, the pre-existing rows that
are causing the constraint violation are removed prior to inserting
or updating the current row.
|
static int |
CONFLICT_ROLLBACK
When a constraint violation occurs, an immediate ROLLBACK occurs,
thus ending the current transaction, and the command aborts with a
return code of SQLITE_CONSTRAINT.
|
static int |
CREATE_IF_NECESSARY
Open flag: Flag for
openDatabase(java.lang.String, android.database.sqlite.SQLiteDatabase.CursorFactory, int) to create the database file if it does not
already exist. |
static int |
ENABLE_WRITE_AHEAD_LOGGING
Open flag: Flag for
openDatabase(java.lang.String, android.database.sqlite.SQLiteDatabase.CursorFactory, int) to open the database file with
write-ahead logging enabled by default. |
static int |
MAX_SQL_CACHE_SIZE
Absolute max value that can be set by
setMaxSqlCacheSize(int) . |
static int |
NO_LOCALIZED_COLLATORS
Open flag: Flag for
openDatabase(java.lang.String, android.database.sqlite.SQLiteDatabase.CursorFactory, int) to open the database without support for
localized collators. |
static int |
OPEN_READONLY
Open flag: Flag for
openDatabase(java.lang.String, android.database.sqlite.SQLiteDatabase.CursorFactory, int) to open the database for reading only. |
static int |
OPEN_READWRITE
Open flag: Flag for
openDatabase(java.lang.String, android.database.sqlite.SQLiteDatabase.CursorFactory, int) to open the database for reading and writing. |
static int |
SQLITE_MAX_LIKE_PATTERN_LENGTH
Maximum Length Of A LIKE Or GLOB Pattern
The pattern matching algorithm used in the default LIKE and GLOB implementation
of SQLite can exhibit O(N^2) performance (where N is the number of characters in
the pattern) for certain pathological cases.
|
Modifier and Type | Method and Description |
---|---|
void |
addCustomFunction(String name,
int numArgs,
SQLiteDatabase.CustomFunction function)
Registers a CustomFunction callback as a function that can be called from
SQLite database triggers.
|
void |
beginTransaction()
Begins a transaction in EXCLUSIVE mode.
|
void |
beginTransactionNonExclusive()
Begins a transaction in IMMEDIATE mode.
|
void |
beginTransactionWithListener(SQLiteTransactionListener transactionListener)
Begins a transaction in EXCLUSIVE mode.
|
void |
beginTransactionWithListenerNonExclusive(SQLiteTransactionListener transactionListener)
Begins a transaction in IMMEDIATE mode.
|
SQLiteStatement |
compileStatement(String sql)
Compiles an SQL statement into a reusable pre-compiled statement object.
|
static SQLiteDatabase |
create(SQLiteDatabase.CursorFactory factory)
Create a memory backed SQLite database.
|
int |
delete(String table,
String whereClause,
String[] whereArgs)
Convenience method for deleting rows in the database.
|
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.
|
void |
disableWriteAheadLogging()
This method disables the features enabled by
enableWriteAheadLogging() . |
boolean |
enableWriteAheadLogging()
This method enables parallel execution of queries from multiple threads on the
same database.
|
void |
endTransaction()
End a transaction.
|
void |
execSQL(String sql)
Execute a single SQL statement that is NOT a SELECT
or any other SQL statement that returns data.
|
void |
execSQL(String sql,
Object[] bindArgs)
Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.
|
protected void |
finalize()
Invoked when the garbage collector has detected that this instance is no longer reachable.
|
static String |
findEditTable(String tables)
Finds the name of the first table, which is editable.
|
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.
|
long |
getMaximumSize()
Returns the maximum size the database may grow to.
|
long |
getPageSize()
Returns the current database page size, in bytes.
|
String |
getPath()
Gets the path to the database file.
|
Map<String,String> |
getSyncedTables()
Deprecated.
This method no longer serves any useful purpose and has been deprecated.
|
int |
getVersion()
Gets the database version.
|
long |
insert(String table,
String nullColumnHack,
ContentValues values)
Convenience method for inserting a row into the database.
|
long |
insertOrThrow(String table,
String nullColumnHack,
ContentValues values)
Convenience method for inserting a row into the database.
|
long |
insertWithOnConflict(String table,
String nullColumnHack,
ContentValues initialValues,
int conflictAlgorithm)
General method for inserting a row into the database.
|
boolean |
inTransaction()
Returns true if the current thread has a transaction pending.
|
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.
|
boolean |
isDbLockedByCurrentThread()
Returns true if the current thread is holding an active connection to the database.
|
boolean |
isDbLockedByOtherThreads()
Deprecated.
Always returns false. Do not use this method.
|
boolean |
isInMemoryDatabase()
Returns true if the database is in-memory db.
|
boolean |
isOpen()
Returns true if the database is currently open.
|
boolean |
isReadOnly()
Returns true if the database is opened as read only.
|
boolean |
isWriteAheadLoggingEnabled()
Returns true if write-ahead logging has been enabled for this database.
|
void |
markTableSyncable(String table,
String deletedTable)
Deprecated.
This method no longer serves any useful purpose and has been deprecated.
|
void |
markTableSyncable(String table,
String foreignKey,
String updateTable)
Deprecated.
This method no longer serves any useful purpose and has been deprecated.
|
boolean |
needUpgrade(int newVersion)
Returns true if the new version code is greater than the current database version.
|
protected void |
onAllReferencesReleased()
Called when the last reference to the object was released by
a call to
SQLiteClosable.releaseReference() or SQLiteClosable.close() . |
static SQLiteDatabase |
openDatabase(String path,
SQLiteDatabase.CursorFactory factory,
int flags)
Open the database according to the flags
OPEN_READWRITE
OPEN_READONLY CREATE_IF_NECESSARY and/or NO_LOCALIZED_COLLATORS . |
static SQLiteDatabase |
openDatabase(String path,
SQLiteDatabase.CursorFactory factory,
int flags,
DatabaseErrorHandler errorHandler)
Open the database according to the flags
OPEN_READWRITE
OPEN_READONLY CREATE_IF_NECESSARY and/or NO_LOCALIZED_COLLATORS . |
static SQLiteDatabase |
openOrCreateDatabase(File file,
SQLiteDatabase.CursorFactory factory)
Equivalent to openDatabase(file.getPath(), factory, CREATE_IF_NECESSARY).
|
static SQLiteDatabase |
openOrCreateDatabase(String path,
SQLiteDatabase.CursorFactory factory)
Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY).
|
static SQLiteDatabase |
openOrCreateDatabase(String path,
SQLiteDatabase.CursorFactory factory,
DatabaseErrorHandler errorHandler)
Equivalent to openDatabase(path, factory, CREATE_IF_NECESSARY, errorHandler).
|
Cursor |
query(boolean distinct,
String table,
String[] columns,
String selection,
String[] selectionArgs,
String groupBy,
String having,
String orderBy,
String limit)
Query the given URL, returning a
Cursor over the result set. |
Cursor |
query(boolean distinct,
String table,
String[] columns,
String selection,
String[] selectionArgs,
String groupBy,
String having,
String orderBy,
String limit,
CancellationSignal cancellationSignal)
Query the given URL, returning a
Cursor over the result set. |
Cursor |
query(String table,
String[] columns,
String selection,
String[] selectionArgs,
String groupBy,
String having,
String orderBy)
Query the given table, returning a
Cursor over the result set. |
Cursor |
query(String table,
String[] columns,
String selection,
String[] selectionArgs,
String groupBy,
String having,
String orderBy,
String limit)
Query the given table, returning a
Cursor over the result set. |
Cursor |
queryWithFactory(SQLiteDatabase.CursorFactory cursorFactory,
boolean distinct,
String table,
String[] columns,
String selection,
String[] selectionArgs,
String groupBy,
String having,
String orderBy,
String limit)
Query the given URL, returning a
Cursor over the result set. |
Cursor |
queryWithFactory(SQLiteDatabase.CursorFactory cursorFactory,
boolean distinct,
String table,
String[] columns,
String selection,
String[] selectionArgs,
String groupBy,
String having,
String orderBy,
String limit,
CancellationSignal cancellationSignal)
Query the given URL, returning a
Cursor over the result set. |
Cursor |
rawQuery(String sql,
String[] selectionArgs)
Runs the provided SQL and returns a
Cursor over the result set. |
Cursor |
rawQuery(String sql,
String[] selectionArgs,
CancellationSignal cancellationSignal)
Runs the provided SQL and returns a
Cursor over the result set. |
Cursor |
rawQueryWithFactory(SQLiteDatabase.CursorFactory cursorFactory,
String sql,
String[] selectionArgs,
String editTable)
Runs the provided SQL and returns a cursor over the result set.
|
Cursor |
rawQueryWithFactory(SQLiteDatabase.CursorFactory cursorFactory,
String sql,
String[] selectionArgs,
String editTable,
CancellationSignal cancellationSignal)
Runs the provided SQL and returns a cursor over the result set.
|
static int |
releaseMemory()
Attempts to release memory that SQLite holds but does not require to
operate properly.
|
void |
reopenReadWrite()
Reopens the database in read-write mode.
|
long |
replace(String table,
String nullColumnHack,
ContentValues initialValues)
Convenience method for replacing a row in the database.
|
long |
replaceOrThrow(String table,
String nullColumnHack,
ContentValues initialValues)
Convenience method for replacing a row in the database.
|
void |
setForeignKeyConstraintsEnabled(boolean enable)
Sets whether foreign key constraints are enabled for the database.
|
void |
setLocale(Locale locale)
Sets the locale for this database.
|
void |
setLockingEnabled(boolean lockingEnabled)
Deprecated.
This method now does nothing. Do not use.
|
long |
setMaximumSize(long numBytes)
Sets the maximum size the database will grow to.
|
void |
setMaxSqlCacheSize(int cacheSize)
Sets the maximum size of the prepared-statement cache for this database.
|
void |
setPageSize(long numBytes)
Sets the database page size.
|
void |
setTransactionSuccessful()
Marks the current transaction as successful.
|
void |
setVersion(int version)
Sets the database version.
|
String |
toString()
Returns a string containing a concise, human-readable description of this
object.
|
int |
update(String table,
ContentValues values,
String whereClause,
String[] whereArgs)
Convenience method for updating rows in the database.
|
int |
updateWithOnConflict(String table,
ContentValues values,
String whereClause,
String[] whereArgs,
int conflictAlgorithm)
Convenience method for updating rows in the database.
|
boolean |
yieldIfContended()
Deprecated.
if the db is locked more than once (becuase of nested transactions) then the lock
will not be yielded. Use yieldIfContendedSafely instead.
|
boolean |
yieldIfContendedSafely()
Temporarily end the transaction to let other threads run.
|
boolean |
yieldIfContendedSafely(long sleepAfterYieldDelay)
Temporarily end the transaction to let other threads run.
|
acquireReference, close, onAllReferencesReleasedFromContainer, releaseReference, releaseReferenceFromContainer
public static final int CONFLICT_ROLLBACK
public static final int CONFLICT_ABORT
public static final int CONFLICT_FAIL
public static final int CONFLICT_IGNORE
public static final int CONFLICT_REPLACE
public static final int CONFLICT_NONE
public static final int SQLITE_MAX_LIKE_PATTERN_LENGTH
public static final int OPEN_READWRITE
openDatabase(java.lang.String, android.database.sqlite.SQLiteDatabase.CursorFactory, int)
to open the database for reading and writing.
If the disk is full, this may fail even before you actually write anything.
Note that the value of this flag is 0, so it is the default.public static final int OPEN_READONLY
openDatabase(java.lang.String, android.database.sqlite.SQLiteDatabase.CursorFactory, int)
to open the database for reading only.
This is the only reliable way to open a database if the disk may be full.public static final int NO_LOCALIZED_COLLATORS
openDatabase(java.lang.String, android.database.sqlite.SQLiteDatabase.CursorFactory, int)
to open the database without support for
localized collators.
This causes the collator LOCALIZED
not to be created.
You must be consistent when using this flag to use the setting the database was
created with. If this is set, setLocale(java.util.Locale)
will do nothing.public static final int CREATE_IF_NECESSARY
openDatabase(java.lang.String, android.database.sqlite.SQLiteDatabase.CursorFactory, int)
to create the database file if it does not
already exist.public static final int ENABLE_WRITE_AHEAD_LOGGING
openDatabase(java.lang.String, android.database.sqlite.SQLiteDatabase.CursorFactory, int)
to open the database file with
write-ahead logging enabled by default. Using this flag is more efficient
than calling enableWriteAheadLogging()
.
Write-ahead logging cannot be used with read-only databases so the value of
this flag is ignored if the database is opened read-only.public static final int MAX_SQL_CACHE_SIZE
setMaxSqlCacheSize(int)
.
Each prepared-statement is between 1K - 6K, depending on the complexity of the
SQL statement & schema. A large SQL cache may use a significant amount of memory.protected void finalize() throws Throwable
Object
Note that objects that override finalize
are significantly more expensive than
objects that don't. Finalizers may be run a long time after the object is no longer
reachable, depending on memory pressure, so it's a bad idea to rely on them for cleanup.
Note also that finalizers are run on a single VM-wide finalizer thread,
so doing blocking work in a finalizer is a bad idea. A finalizer is usually only necessary
for a class that has a native peer and needs to call a native method to destroy that peer.
Even then, it's better to provide an explicit close
method (and implement
Closeable
), and insist that callers manually dispose of instances. This
works well for something like files, but less well for something like a BigInteger
where typical calling code would have to deal with lots of temporaries. Unfortunately,
code that creates lots of temporaries is the worst kind of code from the point of view of
the single finalizer thread.
If you must use finalizers, consider at least providing your own
ReferenceQueue
and having your own thread process that queue.
Unlike constructors, finalizers are not automatically chained. You are responsible for
calling super.finalize()
yourself.
Uncaught exceptions thrown by finalizers are ignored and do not terminate the finalizer thread. See Effective Java Item 7, "Avoid finalizers" for more.
protected void onAllReferencesReleased()
SQLiteClosable
SQLiteClosable.releaseReference()
or SQLiteClosable.close()
.onAllReferencesReleased
in class SQLiteClosable
public static int releaseMemory()
@Deprecated public void setLockingEnabled(boolean lockingEnabled)
lockingEnabled
- set to true to enable locks, false otherwisepublic void beginTransaction()
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(); }
public void beginTransactionNonExclusive()
Here is the standard idiom for transactions:
db.beginTransactionNonExclusive(); try { ... db.setTransactionSuccessful(); } finally { db.endTransaction(); }
public void beginTransactionWithListener(SQLiteTransactionListener transactionListener)
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(); }
transactionListener
- listener that should be notified when the transaction begins,
commits, or is rolled back, either explicitly or by a call to
yieldIfContendedSafely()
.public void beginTransactionWithListenerNonExclusive(SQLiteTransactionListener transactionListener)
Here is the standard idiom for transactions:
db.beginTransactionWithListenerNonExclusive(listener); try { ... db.setTransactionSuccessful(); } finally { db.endTransaction(); }
transactionListener
- listener that should be notified when the
transaction begins, commits, or is rolled back, either
explicitly or by a call to yieldIfContendedSafely()
.public void endTransaction()
public void setTransactionSuccessful()
IllegalStateException
- if the current thread is not in a transaction or the
transaction is already marked as successful.public boolean inTransaction()
public boolean isDbLockedByCurrentThread()
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.
@Deprecated public boolean isDbLockedByOtherThreads()
There is no longer the concept of a database lock, so this method always returns false.
@Deprecated public boolean yieldIfContended()
public boolean yieldIfContendedSafely()
public boolean yieldIfContendedSafely(long sleepAfterYieldDelay)
sleepAfterYieldDelay
- if > 0, sleep this long before starting a new transaction if
the lock was actually yielded. This will allow other background threads to make some
more progress than they would if we started the transaction immediately.@Deprecated public Map<String,String> getSyncedTables()
public static SQLiteDatabase openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)
OPEN_READWRITE
OPEN_READONLY
CREATE_IF_NECESSARY
and/or NO_LOCALIZED_COLLATORS
.
Sets the locale of the database to the the system's current locale.
Call setLocale(java.util.Locale)
if you would like something else.
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 modeSQLiteException
- if the database cannot be openedpublic static SQLiteDatabase openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags, DatabaseErrorHandler errorHandler)
OPEN_READWRITE
OPEN_READONLY
CREATE_IF_NECESSARY
and/or NO_LOCALIZED_COLLATORS
.
Sets the locale of the database to the the system's current locale.
Call setLocale(java.util.Locale)
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.
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 corruptionSQLiteException
- if the database cannot be openedpublic static SQLiteDatabase openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)
public static SQLiteDatabase openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)
public static SQLiteDatabase openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler)
public static boolean deleteDatabase(File file)
file
- The database file path.public void reopenReadWrite()
SQLiteException
- if the database could not be reopened as requested, in which
case it remains open in read only mode.IllegalStateException
- if the database is not open.isReadOnly()
public static SQLiteDatabase create(SQLiteDatabase.CursorFactory factory)
Sets the locale of the database to the the system's current locale.
Call setLocale(java.util.Locale)
if you would like something else.
factory
- an optional factory class that is called to instantiate a
cursor when query is calledpublic void addCustomFunction(String name, int numArgs, SQLiteDatabase.CustomFunction function)
name
- the name of the sqlite3 functionnumArgs
- the number of arguments for the functionfunction
- callback to call when the function is executedpublic int getVersion()
public void setVersion(int version)
version
- the new database versionpublic long getMaximumSize()
public long setMaximumSize(long numBytes)
numBytes
- the maximum database size, in bytespublic long getPageSize()
public void setPageSize(long numBytes)
numBytes
- the database page size, in bytes@Deprecated public void markTableSyncable(String table, String deletedTable)
table
- the table to mark as syncabledeletedTable
- The deleted table that corresponds to the
syncable table@Deprecated public void markTableSyncable(String table, String foreignKey, String updateTable)
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_dirtypublic static String findEditTable(String tables)
tables
- a list of tablespublic SQLiteStatement compileStatement(String sql) throws SQLException
execSQL(String)
. You may put ?s in the
statement and fill in those values with SQLiteProgram.bindString(int, java.lang.String)
and SQLiteProgram.bindLong(int, long)
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.
sql
- The raw SQL statement, may contain ? for unknown values to be
bound later.SQLiteStatement
object. Note that
SQLiteStatement
s are not synchronized, see the documentation for more details.SQLException
public Cursor query(boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
Cursor
over the result set.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. Passing null will
return all columns, which is discouraged to prevent reading
data from storage that isn't going to be used.selection
- A filter declaring which rows to return, formatted as an
SQL WHERE clause (excluding the WHERE itself). Passing null
will return all rows for the given table.selectionArgs
- You may include ?s in selection, which will be
replaced by the values from selectionArgs, in order that they
appear in the selection. The values will be bound as Strings.groupBy
- A filter declaring how to group rows, formatted as an SQL
GROUP BY clause (excluding the GROUP BY itself). Passing null
will cause the rows to not be grouped.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). Passing null will cause
all row groups to be included, and is required when row
grouping is not being used.orderBy
- How to order the rows, formatted as an SQL ORDER BY clause
(excluding the ORDER BY itself). Passing null will use the
default sort order, which may be unordered.limit
- Limits the number of rows returned by the query,
formatted as LIMIT clause. Passing null denotes no LIMIT clause.Cursor
object, which is positioned before the first entry. Note that
Cursor
s are not synchronized, see the documentation for more details.Cursor
public Cursor query(boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit, CancellationSignal cancellationSignal)
Cursor
over the result set.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. Passing null will
return all columns, which is discouraged to prevent reading
data from storage that isn't going to be used.selection
- A filter declaring which rows to return, formatted as an
SQL WHERE clause (excluding the WHERE itself). Passing null
will return all rows for the given table.selectionArgs
- You may include ?s in selection, which will be
replaced by the values from selectionArgs, in order that they
appear in the selection. The values will be bound as Strings.groupBy
- A filter declaring how to group rows, formatted as an SQL
GROUP BY clause (excluding the GROUP BY itself). Passing null
will cause the rows to not be grouped.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). Passing null will cause
all row groups to be included, and is required when row
grouping is not being used.orderBy
- How to order the rows, formatted as an SQL ORDER BY clause
(excluding the ORDER BY itself). Passing null will use the
default sort order, which may be unordered.limit
- Limits the number of rows returned by the query,
formatted as LIMIT clause. Passing null denotes no LIMIT clause.cancellationSignal
- A signal to cancel the operation in progress, or null if none.
If the operation is canceled, then OperationCanceledException
will be thrown
when the query is executed.Cursor
object, which is positioned before the first entry. Note that
Cursor
s are not synchronized, see the documentation for more details.Cursor
public Cursor queryWithFactory(SQLiteDatabase.CursorFactory cursorFactory, boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
Cursor
over the result set.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. Passing null will
return all columns, which is discouraged to prevent reading
data from storage that isn't going to be used.selection
- A filter declaring which rows to return, formatted as an
SQL WHERE clause (excluding the WHERE itself). Passing null
will return all rows for the given table.selectionArgs
- You may include ?s in selection, which will be
replaced by the values from selectionArgs, in order that they
appear in the selection. The values will be bound as Strings.groupBy
- A filter declaring how to group rows, formatted as an SQL
GROUP BY clause (excluding the GROUP BY itself). Passing null
will cause the rows to not be grouped.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). Passing null will cause
all row groups to be included, and is required when row
grouping is not being used.orderBy
- How to order the rows, formatted as an SQL ORDER BY clause
(excluding the ORDER BY itself). Passing null will use the
default sort order, which may be unordered.limit
- Limits the number of rows returned by the query,
formatted as LIMIT clause. Passing null denotes no LIMIT clause.Cursor
object, which is positioned before the first entry. Note that
Cursor
s are not synchronized, see the documentation for more details.Cursor
public Cursor queryWithFactory(SQLiteDatabase.CursorFactory cursorFactory, boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit, CancellationSignal cancellationSignal)
Cursor
over the result set.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. Passing null will
return all columns, which is discouraged to prevent reading
data from storage that isn't going to be used.selection
- A filter declaring which rows to return, formatted as an
SQL WHERE clause (excluding the WHERE itself). Passing null
will return all rows for the given table.selectionArgs
- You may include ?s in selection, which will be
replaced by the values from selectionArgs, in order that they
appear in the selection. The values will be bound as Strings.groupBy
- A filter declaring how to group rows, formatted as an SQL
GROUP BY clause (excluding the GROUP BY itself). Passing null
will cause the rows to not be grouped.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). Passing null will cause
all row groups to be included, and is required when row
grouping is not being used.orderBy
- How to order the rows, formatted as an SQL ORDER BY clause
(excluding the ORDER BY itself). Passing null will use the
default sort order, which may be unordered.limit
- Limits the number of rows returned by the query,
formatted as LIMIT clause. Passing null denotes no LIMIT clause.cancellationSignal
- A signal to cancel the operation in progress, or null if none.
If the operation is canceled, then OperationCanceledException
will be thrown
when the query is executed.Cursor
object, which is positioned before the first entry. Note that
Cursor
s are not synchronized, see the documentation for more details.Cursor
public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
Cursor
over the result set.table
- The table name to compile the query against.columns
- A list of which columns to return. Passing null will
return all columns, which is discouraged to prevent reading
data from storage that isn't going to be used.selection
- A filter declaring which rows to return, formatted as an
SQL WHERE clause (excluding the WHERE itself). Passing null
will return all rows for the given table.selectionArgs
- You may include ?s in selection, which will be
replaced by the values from selectionArgs, in order that they
appear in the selection. The values will be bound as Strings.groupBy
- A filter declaring how to group rows, formatted as an SQL
GROUP BY clause (excluding the GROUP BY itself). Passing null
will cause the rows to not be grouped.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). Passing null will cause
all row groups to be included, and is required when row
grouping is not being used.orderBy
- How to order the rows, formatted as an SQL ORDER BY clause
(excluding the ORDER BY itself). Passing null will use the
default sort order, which may be unordered.Cursor
object, which is positioned before the first entry. Note that
Cursor
s are not synchronized, see the documentation for more details.Cursor
public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
Cursor
over the result set.table
- The table name to compile the query against.columns
- A list of which columns to return. Passing null will
return all columns, which is discouraged to prevent reading
data from storage that isn't going to be used.selection
- A filter declaring which rows to return, formatted as an
SQL WHERE clause (excluding the WHERE itself). Passing null
will return all rows for the given table.selectionArgs
- You may include ?s in selection, which will be
replaced by the values from selectionArgs, in order that they
appear in the selection. The values will be bound as Strings.groupBy
- A filter declaring how to group rows, formatted as an SQL
GROUP BY clause (excluding the GROUP BY itself). Passing null
will cause the rows to not be grouped.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). Passing null will cause
all row groups to be included, and is required when row
grouping is not being used.orderBy
- How to order the rows, formatted as an SQL ORDER BY clause
(excluding the ORDER BY itself). Passing null will use the
default sort order, which may be unordered.limit
- Limits the number of rows returned by the query,
formatted as LIMIT clause. Passing null denotes no LIMIT clause.Cursor
object, which is positioned before the first entry. Note that
Cursor
s are not synchronized, see the documentation for more details.Cursor
public Cursor rawQuery(String sql, String[] selectionArgs)
Cursor
over the result set.sql
- the SQL query. The SQL string must not be ; terminatedselectionArgs
- You may include ?s in where clause in the query,
which will be replaced by the values from selectionArgs. The
values will be bound as Strings.Cursor
object, which is positioned before the first entry. Note that
Cursor
s are not synchronized, see the documentation for more details.public Cursor rawQuery(String sql, String[] selectionArgs, CancellationSignal cancellationSignal)
Cursor
over the result set.sql
- the SQL query. The SQL string must not be ; terminatedselectionArgs
- You may include ?s in where clause in the query,
which will be replaced by the values from selectionArgs. The
values will be bound as Strings.cancellationSignal
- A signal to cancel the operation in progress, or null if none.
If the operation is canceled, then OperationCanceledException
will be thrown
when the query is executed.Cursor
object, which is positioned before the first entry. Note that
Cursor
s are not synchronized, see the documentation for more details.public Cursor rawQueryWithFactory(SQLiteDatabase.CursorFactory cursorFactory, String sql, String[] selectionArgs, String editTable)
cursorFactory
- the cursor factory to use, or null for the default factorysql
- the SQL query. The SQL string must not be ; terminatedselectionArgs
- You may include ?s in where clause in the query,
which will be replaced by the values from selectionArgs. The
values will be bound as Strings.editTable
- the name of the first table, which is editableCursor
object, which is positioned before the first entry. Note that
Cursor
s are not synchronized, see the documentation for more details.public Cursor rawQueryWithFactory(SQLiteDatabase.CursorFactory cursorFactory, String sql, String[] selectionArgs, String editTable, CancellationSignal cancellationSignal)
cursorFactory
- the cursor factory to use, or null for the default factorysql
- the SQL query. The SQL string must not be ; terminatedselectionArgs
- You may include ?s in where clause in the query,
which will be replaced by the values from selectionArgs. The
values will be bound as Strings.editTable
- the name of the first table, which is editablecancellationSignal
- A signal to cancel the operation in progress, or null if none.
If the operation is canceled, then OperationCanceledException
will be thrown
when the query is executed.Cursor
object, which is positioned before the first entry. Note that
Cursor
s are not synchronized, see the documentation for more details.public long insert(String table, String nullColumnHack, ContentValues values)
table
- the table to insert the row intonullColumnHack
- optional; may be null
.
SQL doesn't allow inserting a completely empty row without
naming at least one column name. If your provided values
is
empty, no column names are known and an empty row can't be inserted.
If not set to null, the nullColumnHack
parameter
provides the name of nullable column name to explicitly insert a NULL into
in the case where your values
is empty.values
- this map contains the initial column values for the
row. The keys should be the column names and the values the
column valuespublic long insertOrThrow(String table, String nullColumnHack, ContentValues values) throws SQLException
table
- the table to insert the row intonullColumnHack
- optional; may be null
.
SQL doesn't allow inserting a completely empty row without
naming at least one column name. If your provided values
is
empty, no column names are known and an empty row can't be inserted.
If not set to null, the nullColumnHack
parameter
provides the name of nullable column name to explicitly insert a NULL into
in the case where your values
is empty.values
- this map contains the initial column values for the
row. The keys should be the column names and the values the
column valuesSQLException
public long replace(String table, String nullColumnHack, ContentValues initialValues)
table
- the table in which to replace the rownullColumnHack
- optional; may be null
.
SQL doesn't allow inserting a completely empty row without
naming at least one column name. If your provided initialValues
is
empty, no column names are known and an empty row can't be inserted.
If not set to null, the nullColumnHack
parameter
provides the name of nullable column name to explicitly insert a NULL into
in the case where your initialValues
is empty.initialValues
- this map contains the initial column values for
the row.public long replaceOrThrow(String table, String nullColumnHack, ContentValues initialValues) throws SQLException
table
- the table in which to replace the rownullColumnHack
- optional; may be null
.
SQL doesn't allow inserting a completely empty row without
naming at least one column name. If your provided initialValues
is
empty, no column names are known and an empty row can't be inserted.
If not set to null, the nullColumnHack
parameter
provides the name of nullable column name to explicitly insert a NULL into
in the case where your initialValues
is empty.initialValues
- this map contains the initial column values for
the row. The keySQLException
public long insertWithOnConflict(String table, String nullColumnHack, ContentValues initialValues, int conflictAlgorithm)
table
- the table to insert the row intonullColumnHack
- optional; may be null
.
SQL doesn't allow inserting a completely empty row without
naming at least one column name. If your provided initialValues
is
empty, no column names are known and an empty row can't be inserted.
If not set to null, the nullColumnHack
parameter
provides the name of nullable column name to explicitly insert a NULL into
in the case where your initialValues
is empty.initialValues
- this map contains the initial column values for the
row. The keys should be the column names and the values the
column valuesconflictAlgorithm
- for insert conflict resolverCONFLICT_IGNORE
OR -1 if any errorpublic int delete(String table, String whereClause, String[] whereArgs)
table
- the table to delete fromwhereClause
- the optional WHERE clause to apply when deleting.
Passing null will delete all rows.public int update(String table, ContentValues values, String whereClause, String[] whereArgs)
table
- the table to update invalues
- a map from column names to new column values. null is a
valid value that will be translated to NULL.whereClause
- the optional WHERE clause to apply when updating.
Passing null will update all rows.public int updateWithOnConflict(String table, ContentValues values, String whereClause, String[] whereArgs, int conflictAlgorithm)
table
- the table to update invalues
- a map from column names to new column values. null is a
valid value that will be translated to NULL.whereClause
- the optional WHERE clause to apply when updating.
Passing null will update all rows.conflictAlgorithm
- for update conflict resolverpublic void execSQL(String sql) throws SQLException
It has no means to return any data (such as the number of affected rows).
Instead, you're encouraged to use insert(String, String, ContentValues)
,
update(String, ContentValues, String, String[])
, 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'enableWriteAheadLogging()
sql
- the SQL statement to be executed. Multiple statements separated by semicolons are
not supported.SQLException
- if the SQL string is invalidpublic void execSQL(String sql, Object[] bindArgs) throws SQLException
For INSERT statements, use any of the following instead.
insert(String, String, ContentValues)
insertOrThrow(String, String, ContentValues)
insertWithOnConflict(String, String, ContentValues, int)
For UPDATE statements, use any of the following instead.
update(String, ContentValues, String, String[])
updateWithOnConflict(String, ContentValues, String, String[], int)
For DELETE statements, use any of the following instead.
For example, the following are good candidates for using this method:
When using enableWriteAheadLogging()
, journal_mode is
automatically managed by this class. So, do not set journal_mode
using "PRAGMA journal_mode'enableWriteAheadLogging()
sql
- the SQL statement to be executed. Multiple statements separated by semicolons are
not supported.bindArgs
- only byte[], String, Long and Double are supported in bindArgs.SQLException
- if the SQL string is invalidpublic boolean isReadOnly()
public boolean isInMemoryDatabase()
public boolean isOpen()
public boolean needUpgrade(int newVersion)
newVersion
- The new version code.public final String getPath()
public void setLocale(Locale locale)
NO_LOCALIZED_COLLATORS
flag set or was opened read only.locale
- The new locale.SQLException
- if the locale could not be set. The most common reason
for this is that there is no collator available for the locale you requested.
In this case the database remains unchanged.public void setMaxSqlCacheSize(int cacheSize)
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.
cacheSize
- the size of the cache. can be (0 to MAX_SQL_CACHE_SIZE
)IllegalStateException
- if input cacheSize > MAX_SQL_CACHE_SIZE
.public void setForeignKeyConstraintsEnabled(boolean enable)
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(java.io.File, android.database.sqlite.SQLiteDatabase.CursorFactory)
or in the SQLiteOpenHelper.onConfigure(android.database.sqlite.SQLiteDatabase)
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.
enable
- True to enable foreign key constraints, false to disable them.IllegalStateException
- if the are transactions is in progress
when this method is called.public boolean enableWriteAheadLogging()
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(SQLiteTransactionListener)
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(java.lang.String, android.database.sqlite.SQLiteDatabase.CursorFactory, int)
. 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.
IllegalStateException
- if there are transactions in progress at the
time this method is called. WAL mode can only be changed when there are no
transactions in progress.ENABLE_WRITE_AHEAD_LOGGING
,
disableWriteAheadLogging()
public void disableWriteAheadLogging()
enableWriteAheadLogging()
.IllegalStateException
- if there are transactions in progress at the
time this method is called. WAL mode can only be changed when there are no
transactions in progress.enableWriteAheadLogging()
public boolean isWriteAheadLoggingEnabled()
enableWriteAheadLogging()
,
ENABLE_WRITE_AHEAD_LOGGING
public List<Pair<String,String>> getAttachedDbs()
public boolean isDatabaseIntegrityOk()
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.
public String toString()
Object
getClass().getName() + '@' + Integer.toHexString(hashCode())
See Writing a useful
toString
method
if you intend implementing your own toString
method.