Class SQLiteConnection
- java.lang.Object
-
- android.database.sqlite.SQLiteConnection
-
- All Implemented Interfaces:
CancellationSignal.OnCancelListener
public final class SQLiteConnection extends Object implements CancellationSignal.OnCancelListener
Represents a SQLite database connection. Each connection wraps an instance of a nativesqlite3object.When database connection pooling is enabled, there can be multiple active connections to the same database. Otherwise there is typically only one connection per database.
When the SQLite WAL feature is enabled, multiple readers and one writer can concurrently access the database. Without WAL, readers and writers are mutually exclusive.
Ownership and concurrency guarantees
Connection objects are not thread-safe. They are acquired as needed to perform a database operation and are then returned to the pool. At any given time, a connection is either owned and used by a
SQLiteSessionobject or theSQLiteConnectionPool. Those classes are responsible for serializing operations to guard against concurrent use of a connection.The guarantee of having a single owner allows this class to be implemented without locks and greatly simplifies resource management.
Encapsulation guarantees
The connection object object owns *all* of the SQLite related native objects that are associated with the connection. What's more, there are no other objects in the system that are capable of obtaining handles to those native objects. Consequently, when the connection is closed, we do not have to worry about what other components might have references to its associated SQLite state -- there are none.
Encapsulation is what ensures that the connection object's lifecycle does not become a tortured mess of finalizers and reference queues.
Reentrance
This class must tolerate reentrant execution of SQLite operations because triggers may call custom SQLite functions that perform additional queries.
-
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description voiddump(Printer printer, boolean verbose)Dumps debugging information about this connection.voidexecute(String sql, Object[] bindArgs, CancellationSignal cancellationSignal)Executes a statement that does not return a result.ParcelFileDescriptorexecuteForBlobFileDescriptor(String sql, Object[] bindArgs, CancellationSignal cancellationSignal)Executes a statement that returns a single BLOB result as a file descriptor to a shared memory region.intexecuteForChangedRowCount(String sql, Object[] bindArgs, CancellationSignal cancellationSignal)Executes a statement that returns a count of the number of rows that were changed.intexecuteForCursorWindow(String sql, Object[] bindArgs, CursorWindow window, int startPos, int requiredPos, boolean countAllRows, CancellationSignal cancellationSignal)Executes a statement and populates the specifiedCursorWindowwith a range of results.longexecuteForLastInsertedRowId(String sql, Object[] bindArgs, CancellationSignal cancellationSignal)Executes a statement that returns the row id of the last row inserted by the statement.longexecuteForLong(String sql, Object[] bindArgs, CancellationSignal cancellationSignal)Executes a statement that returns a singlelongresult.StringexecuteForString(String sql, Object[] bindArgs, CancellationSignal cancellationSignal)Executes a statement that returns a singleStringresult.protected voidfinalize()Invoked when the garbage collector has detected that this instance is no longer reachable.intgetConnectionId()Gets the unique id of this connection.booleanisPrimaryConnection()Returns true if this is the primary database connection.voidonCancel()Called whenCancellationSignal.cancel()is invoked.voidprepare(String sql, SQLiteStatementInfo outStatementInfo)Prepares a statement for execution but does not bind its parameters or execute it.StringtoString()Returns a string containing a concise, human-readable description of this object.
-
-
-
Method Detail
-
finalize
protected void finalize() throws ThrowableDescription copied from class:ObjectInvoked when the garbage collector has detected that this instance is no longer reachable. The default implementation does nothing, but this method can be overridden to free resources.Note that objects that override
finalizeare 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 explicitclosemethod (and implementCloseable), and insist that callers manually dispose of instances. This works well for something like files, but less well for something like aBigIntegerwhere 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
ReferenceQueueand 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.
-
getConnectionId
public int getConnectionId()
Gets the unique id of this connection.- Returns:
- The connection id.
-
isPrimaryConnection
public boolean isPrimaryConnection()
Returns true if this is the primary database connection.- Returns:
- True if this is the primary database connection.
-
prepare
public void prepare(String sql, SQLiteStatementInfo outStatementInfo)
Prepares a statement for execution but does not bind its parameters or execute it.This method can be used to check for syntax errors during compilation prior to execution of the statement. If the
outStatementInfoargument is not null, the providedSQLiteStatementInfoobject is populated with information about the statement.A prepared statement makes no reference to the arguments that may eventually be bound to it, consequently it it possible to cache certain prepared statements such as SELECT or INSERT/UPDATE statements. If the statement is cacheable, then it will be stored in the cache for later.
To take advantage of this behavior as an optimization, the connection pool provides a method to acquire a connection that already has a given SQL statement in its prepared statement cache so that it is ready for execution.
- Parameters:
sql- The SQL statement to prepare.outStatementInfo- TheSQLiteStatementInfoobject to populate with information about the statement, or null if none.- Throws:
SQLiteException- if an error occurs, such as a syntax error.
-
execute
public void execute(String sql, Object[] bindArgs, CancellationSignal cancellationSignal)
Executes a statement that does not return a result.- Parameters:
sql- The SQL statement to execute.bindArgs- The arguments to bind, or null if none.cancellationSignal- A signal to cancel the operation in progress, or null if none.- Throws:
SQLiteException- if an error occurs, such as a syntax error or invalid number of bind arguments.OperationCanceledException- if the operation was canceled.
-
executeForLong
public long executeForLong(String sql, Object[] bindArgs, CancellationSignal cancellationSignal)
Executes a statement that returns a singlelongresult.- Parameters:
sql- The SQL statement to execute.bindArgs- The arguments to bind, or null if none.cancellationSignal- A signal to cancel the operation in progress, or null if none.- Returns:
- The value of the first column in the first row of the result set
as a
long, or zero if none. - Throws:
SQLiteException- if an error occurs, such as a syntax error or invalid number of bind arguments.OperationCanceledException- if the operation was canceled.
-
executeForString
public String executeForString(String sql, Object[] bindArgs, CancellationSignal cancellationSignal)
Executes a statement that returns a singleStringresult.- Parameters:
sql- The SQL statement to execute.bindArgs- The arguments to bind, or null if none.cancellationSignal- A signal to cancel the operation in progress, or null if none.- Returns:
- The value of the first column in the first row of the result set
as a
String, or null if none. - Throws:
SQLiteException- if an error occurs, such as a syntax error or invalid number of bind arguments.OperationCanceledException- if the operation was canceled.
-
executeForBlobFileDescriptor
public ParcelFileDescriptor executeForBlobFileDescriptor(String sql, Object[] bindArgs, CancellationSignal cancellationSignal)
Executes a statement that returns a single BLOB result as a file descriptor to a shared memory region.- Parameters:
sql- The SQL statement to execute.bindArgs- The arguments to bind, or null if none.cancellationSignal- A signal to cancel the operation in progress, or null if none.- Returns:
- The file descriptor for a shared memory region that contains the value of the first column in the first row of the result set as a BLOB, or null if none.
- Throws:
SQLiteException- if an error occurs, such as a syntax error or invalid number of bind arguments.OperationCanceledException- if the operation was canceled.
-
executeForChangedRowCount
public int executeForChangedRowCount(String sql, Object[] bindArgs, CancellationSignal cancellationSignal)
Executes a statement that returns a count of the number of rows that were changed. Use for UPDATE or DELETE SQL statements.- Parameters:
sql- The SQL statement to execute.bindArgs- The arguments to bind, or null if none.cancellationSignal- A signal to cancel the operation in progress, or null if none.- Returns:
- The number of rows that were changed.
- Throws:
SQLiteException- if an error occurs, such as a syntax error or invalid number of bind arguments.OperationCanceledException- if the operation was canceled.
-
executeForLastInsertedRowId
public long executeForLastInsertedRowId(String sql, Object[] bindArgs, CancellationSignal cancellationSignal)
Executes a statement that returns the row id of the last row inserted by the statement. Use for INSERT SQL statements.- Parameters:
sql- The SQL statement to execute.bindArgs- The arguments to bind, or null if none.cancellationSignal- A signal to cancel the operation in progress, or null if none.- Returns:
- The row id of the last row that was inserted, or 0 if none.
- Throws:
SQLiteException- if an error occurs, such as a syntax error or invalid number of bind arguments.OperationCanceledException- if the operation was canceled.
-
executeForCursorWindow
public int executeForCursorWindow(String sql, Object[] bindArgs, CursorWindow window, int startPos, int requiredPos, boolean countAllRows, CancellationSignal cancellationSignal)
Executes a statement and populates the specifiedCursorWindowwith a range of results. Returns the number of rows that were counted during query execution.- Parameters:
sql- The SQL statement to execute.bindArgs- The arguments to bind, or null if none.window- The cursor window to clear and fill.startPos- The start position for filling the window.requiredPos- The position of a row that MUST be in the window. If it won't fit, then the query should discard part of what it filled so that it does. Must be greater than or equal tostartPos.countAllRows- True to count all rows that the query would return regagless of whether they fit in the window.cancellationSignal- A signal to cancel the operation in progress, or null if none.- Returns:
- The number of rows that were counted during query execution. Might
not be all rows in the result set unless
countAllRowsis true. - Throws:
SQLiteException- if an error occurs, such as a syntax error or invalid number of bind arguments.OperationCanceledException- if the operation was canceled.
-
onCancel
public void onCancel()
Description copied from interface:CancellationSignal.OnCancelListenerCalled whenCancellationSignal.cancel()is invoked.- Specified by:
onCancelin interfaceCancellationSignal.OnCancelListener
-
dump
public void dump(Printer printer, boolean verbose)
Dumps debugging information about this connection.- Parameters:
printer- The printer to receive the dump, not null.verbose- True to dump more verbose information.
-
toString
public String toString()
Description copied from class:ObjectReturns a string containing a concise, human-readable description of this object. Subclasses are encouraged to override this method and provide an implementation that takes into account the object's type and data. The default implementation is equivalent to the following expression:getClass().getName() + '@' + Integer.toHexString(hashCode())
See Writing a useful
toStringmethod if you intend implementing your owntoStringmethod.
-
-