FMDatabase
@interface FMDatabase : NSObject
A SQLite (https://sqlite.org/) Objective-C wrapper.
Usage
The three main classes in FMDB are:
FMDatabase- Represents a single SQLite database. Used for executing SQL statements.FMResultSet- Represents the results of executing a query on anFMDatabase.FMDatabaseQueue- If you want to perform queries and updates on multiple threads, you’ll want to use this class.
See also
FMDatabasePool- A pool ofFMDatabaseobjectsFMStatement- A wrapper forsqlite_stmt
External links
- FMDB on GitHub including introductory documentation
- SQLite web site
- FMDB mailing list
Warning
Do not instantiate a single FMDatabase object and use it across multiple threads. Instead, use FMDatabaseQueue .
-
Whether should trace execution
Declaration
Objective-C
@property BOOL traceExecution;Swift
var traceExecution: Bool { get set } -
Whether checked out or not
Declaration
Objective-C
@property BOOL checkedOut;Swift
var checkedOut: Bool { get set } -
Crash on errors
Declaration
Objective-C
@property BOOL crashOnErrors;Swift
var crashOnErrors: Bool { get set } -
Logs errors
Declaration
Objective-C
@property BOOL logsErrors;Swift
var logsErrors: Bool { get set } -
Dictionary of cached statements
Declaration
Objective-C
@property (retain, nullable) NSMutableDictionary *cachedStatements;Swift
var cachedStatements: NSMutableDictionary? { get set }
-
Create a
FMDatabaseobject.An
FMDatabaseis created with a path to a SQLite database file. This path can be one of these three:A file system path. The file does not have to exist on disk. If it does not exist, it is created for you.
An zero-length string. An empty database is created at a temporary location. This database is deleted with the
FMDatabaseconnection is closed.nil. An in-memory database is created. This database will be destroyed with theFMDatabaseconnection is closed.
For example, to open a database in the app’s “Application Support” directory:
NSURL *folder = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:true error:&error]; NSURL *fileURL = [folder URLByAppendingPathComponent:@"test.db"]; FMDatabase *db = [FMDatabase databaseWithPath:fileURL.path];(For more information on temporary and in-memory databases, read the sqlite documentation on the subject: https://sqlite.org/inmemorydb.html)
Declaration
Objective-C
+ (nonnull instancetype)databaseWithPath:(NSString *_Nullable)inPath;Parameters
inPathPath of database file
Return Value
FMDatabaseobject if successful;nilif failure. -
Create a
FMDatabaseobject.An
FMDatabaseis created with a path to a SQLite database file. This path can be one of these three:A file system URL. The file does not have to exist on disk. If it does not exist, it is created for you.
nil. An in-memory database is created. This database will be destroyed with theFMDatabaseconnection is closed.
For example, to open a database in the app’s “Application Support” directory:
NSURL *folder = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:true error:&error]; NSURL *fileURL = [folder URLByAppendingPathComponent:@"test.db"]; FMDatabase *db = [FMDatabase databaseWithURL:fileURL];(For more information on temporary and in-memory databases, read the sqlite documentation on the subject: https://sqlite.org/inmemorydb.html)
Declaration
Objective-C
+ (nonnull instancetype)databaseWithURL:(NSURL *_Nullable)url;Parameters
urlThe local file URL (not remote URL) of database file
Return Value
FMDatabaseobject if successful;nilif failure. -
Initialize a
FMDatabaseobject.An
FMDatabaseis created with a path to a SQLite database file. This path can be one of these three:A file system path. The file does not have to exist on disk. If it does not exist, it is created for you.
A zero-length string. An empty database is created at a temporary location. This database is deleted with the
FMDatabaseconnection is closed.nil. An in-memory database is created. This database will be destroyed with theFMDatabaseconnection is closed.
For example, to open a database in the app’s “Application Support” directory:
NSURL *folder = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:true error:&error]; NSURL *fileURL = [folder URLByAppendingPathComponent:@"test.db"]; FMDatabase *db = [[FMDatabase alloc] initWithPath:fileURL.path];(For more information on temporary and in-memory databases, read the sqlite documentation on the subject: https://sqlite.org/inmemorydb.html)
Declaration
Objective-C
- (nonnull instancetype)initWithPath:(NSString *_Nullable)path;Swift
init(path: String?)Parameters
pathPath of database file.
Return Value
FMDatabaseobject if successful;nilif failure. -
Initialize a
FMDatabaseobject.An
FMDatabaseis created with a local file URL to a SQLite database file. This path can be one of these three:A file system URL. The file does not have to exist on disk. If it does not exist, it is created for you.
nil. An in-memory database is created. This database will be destroyed with theFMDatabaseconnection is closed.
For example, to open a database in the app’s “Application Support” directory:
NSURL *folder = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:true error:&error]; NSURL *fileURL = [folder URLByAppendingPathComponent:@"test.db"]; FMDatabase *db = [[FMDatabase alloc] initWithURL:fileURL];(For more information on temporary and in-memory databases, read the sqlite documentation on the subject: https://sqlite.org/inmemorydb.html)
Declaration
Objective-C
- (nonnull instancetype)initWithURL:(NSURL *_Nullable)url;Swift
init(url: URL?)Parameters
urlThe file
NSURLof database file.Return Value
FMDatabaseobject if successful;nilif failure.
-
Is the database open or not?
Declaration
Objective-C
@property (nonatomic) BOOL isOpen;Swift
var isOpen: Bool { get set } -
Opening a new database connection
The database is opened for reading and writing, and is created if it does not already exist.
See
See
openWithFlags:
See
close
Declaration
Objective-C
- (BOOL)open;Swift
func open() -> BoolReturn Value
YESif successful,NOon error. -
Opening a new database connection with flags and an optional virtual file system (VFS)
SQLITE_OPEN_READONLYThe database is opened in read-only mode. If the database does not already exist, an error is returned.
SQLITE_OPEN_READWRITEThe database is opened for reading and writing if possible, or reading only if the file is write protected by the operating system. In either case the database must already exist, otherwise an error is returned.
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATEThe database is opened for reading and writing, and is created if it does not already exist. This is the behavior that is always used for
openmethod.See
open
See
close
Declaration
Objective-C
- (BOOL)openWithFlags:(int)flags;Swift
func open(withFlags flags: Int32) -> BoolParameters
flagsOne of the following three values, optionally combined with the
SQLITE_OPEN_NOMUTEX,SQLITE_OPEN_FULLMUTEX,SQLITE_OPEN_SHAREDCACHE,SQLITE_OPEN_PRIVATECACHE, and/orSQLITE_OPEN_URIflags:Return Value
YESif successful,NOon error. -
Opening a new database connection with flags and an optional virtual file system (VFS)
SQLITE_OPEN_READONLYThe database is opened in read-only mode. If the database does not already exist, an error is returned.
SQLITE_OPEN_READWRITEThe database is opened for reading and writing if possible, or reading only if the file is write protected by the operating system. In either case the database must already exist, otherwise an error is returned.
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATEThe database is opened for reading and writing, and is created if it does not already exist. This is the behavior that is always used for
openmethod.See
open
See
close
Declaration
Objective-C
- (BOOL)openWithFlags:(int)flags vfs:(NSString *_Nullable)vfsName;Swift
func open(withFlags flags: Int32, vfs vfsName: String?) -> BoolParameters
flagsOne of the following three values, optionally combined with the
SQLITE_OPEN_NOMUTEX,SQLITE_OPEN_FULLMUTEX,SQLITE_OPEN_SHAREDCACHE,SQLITE_OPEN_PRIVATECACHE, and/orSQLITE_OPEN_URIflags:vfsNameIf vfs is given the value is passed to the vfs parameter of sqlite3_open_v2.
Return Value
YESif successful,NOon error. -
Declaration
Objective-C
- (BOOL)close;Swift
func close() -> BoolReturn Value
YESif success,NOon error. -
Test to see if we have a good connection to the database.
This will confirm whether:
is database open
if open, it will try a simple
SELECTstatement and confirm that it succeeds.
Declaration
Objective-C
@property (nonatomic, readonly) BOOL goodConnection;Swift
var goodConnection: Bool { get }Return Value
YESif everything succeeds,NOon failure.
-
Execute single update statement
This method executes a single SQL update statement (i.e. any SQL that does not return results, such as
UPDATE,INSERT, orDELETE. This method employssqlite3_prepare_v2,sqlite3_bindto bind values to?placeholders in the SQL with the optional list of parameters, andsqlite_stepto perform the update.The optional values provided to this method should be objects (e.g.
NSString,NSNumber,NSNull,NSDate, andNSDataobjects), not fundamental data types (e.g.int,long,NSInteger, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object’sdescriptionmethod.See
lastError
See
lastErrorCode
See
lastErrorMessage
See
Declaration
Objective-C
- (BOOL)executeUpdate:(nonnull NSString *)sql withErrorAndBindings:(NSError *_Nullable *_Nullable)outErr, ...;Parameters
sqlThe SQL to be performed, with optional
?placeholders. This can be followed by iptional parameters to bind to?placeholders in the SQL statement. These should be Objective-C objects (e.g.NSString,NSNumber, etc.), not fundamental C data types (e.g.int, etc.).outErrA reference to the
NSErrorpointer to be updated with an auto releasedNSErrorobject if an error if an error occurs. Ifnil, noNSErrorobject will be returned.Return Value
YESupon success;NOupon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure. -
Deprecated
Use executeUpdate:withErrorAndBindings: instead
Execute single update statement
See
executeUpdate:withErrorAndBindings:
Warning
Deprecated: Please use
<executeUpdate:withErrorAndBindings>instead.Declaration
Objective-C
- (BOOL)update:(nonnull NSString *)sql withErrorAndBindings:(NSError *_Nullable *_Nullable)outErr, ...; -
Execute single update statement
This method executes a single SQL update statement (i.e. any SQL that does not return results, such as
UPDATE,INSERT, orDELETE. This method employssqlite3_prepare_v2,sqlite3_bindto bind values to?placeholders in the SQL with the optional list of parameters, andsqlite_stepto perform the update.The optional values provided to this method should be objects (e.g.
NSString,NSNumber,NSNull,NSDate, andNSDataobjects), not fundamental data types (e.g.int,long,NSInteger, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object’sdescriptionmethod.See
lastError
See
lastErrorCode
See
lastErrorMessage
See
Note
This technique supports the use of
?placeholders in the SQL, automatically binding any supplied value parameters to those placeholders. This approach is more robust than techniques that entail usingstringWithFormatto manually build SQL statements, which can be problematic if the values happened to include any characters that needed to be quoted.Note
You cannot use this method from Swift due to incompatibilities between Swift and Objective-C variadic implementations. Consider using
<executeUpdate:values:>instead.Declaration
Objective-C
- (BOOL)executeUpdate:(nonnull NSString *)sql, ...;Parameters
sqlThe SQL to be performed, with optional
?placeholders, followed by optional parameters to bind to?placeholders in the SQL statement. These should be Objective-C objects (e.g.NSString,NSNumber, etc.), not fundamental C data types (e.g.int, etc.).Return Value
YESupon success;NOupon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure. -
Execute single update statement
This method executes a single SQL update statement (i.e. any SQL that does not return results, such as
UPDATE,INSERT, orDELETE. This method employssqlite3_prepare_v2andsqlite_stepto perform the update. Unlike the otherexecuteUpdatemethods, this uses printf-style formatters (e.g.%s,%d, etc.) to build the SQL. Do not use?placeholders in the SQL if you use this method.See
executeUpdate:
See
lastError
See
lastErrorCode
See
lastErrorMessage
Note
This method does not technically perform a traditional printf-style replacement. What this method actually does is replace the printf-style percent sequences with a SQLite
?placeholder, and then bind values to that placeholder. Thus the following command[db executeUpdateWithFormat:@"INSERT INTO test (name) VALUES (%@)", @"Gus"];is actually replacing the
%@with?placeholder, and then performing something equivalent to<executeUpdate:>[db executeUpdate:@"INSERT INTO test (name) VALUES (?)", @"Gus"];There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite
?placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction withpragmastatements and the like. Second, note the lack of quotation marks in the SQL. TheVALUESclause was notVALUES ('%@')(like you might have to do if you built a SQL statement usingNSStringmethodstringWithFormat), but rather simplyVALUES (%@).Declaration
Objective-C
- (BOOL)executeUpdateWithFormat:(nonnull NSString *)format, ...;Parameters
formatThe SQL to be performed, with
printf-style escape sequences, followed by optional parameters to bind to use in conjunction with theprintf-style escape sequences in the SQL statement.Return Value
YESupon success;NOupon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure. -
Execute single update statement
This method executes a single SQL update statement (i.e. any SQL that does not return results, such as
UPDATE,INSERT, orDELETE. This method employssqlite3_prepare_v2andsqlite3_bindbinding any?placeholders in the SQL with the optional list of parameters.The optional values provided to this method should be objects (e.g.
NSString,NSNumber,NSNull,NSDate, andNSDataobjects), not fundamental data types (e.g.int,long,NSInteger, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object’sdescriptionmethod.See
executeUpdate:values:error:
See
lastError
See
lastErrorCode
See
lastErrorMessage
Declaration
Objective-C
- (BOOL)executeUpdate:(nonnull NSString *)sql withArgumentsInArray:(nonnull NSArray *)arguments;Swift
func executeUpdate(_ sql: String, withArgumentsIn arguments: [Any]) -> BoolParameters
sqlThe SQL to be performed, with optional
?placeholders.argumentsA
NSArrayof objects to be used when binding values to the?placeholders in the SQL statement.Return Value
YESupon success;NOupon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure. -
Execute single update statement
This method executes a single SQL update statement (i.e. any SQL that does not return results, such as
UPDATE,INSERT, orDELETE. This method employssqlite3_prepare_v2andsqlite3_bindbinding any?placeholders in the SQL with the optional list of parameters.The optional values provided to this method should be objects (e.g.
NSString,NSNumber,NSNull,NSDate, andNSDataobjects), not fundamental data types (e.g.int,long,NSInteger, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object’sdescriptionmethod.This is similar to
executeUpdate:withArgumentsInArray:, except that this also accepts a pointer to aNSErrorpointer, so that errors can be returned.In Swift, this throws errors, as if it were defined as follows:
func executeUpdate(sql: String, values: [Any]?) throws -> Bool { }See
lastError
See
lastErrorCode
See
lastErrorMessage
Declaration
Objective-C
- (BOOL)executeUpdate:(nonnull NSString *)sql values:(NSArray *_Nullable)values error:(NSError *_Nullable *_Nullable)error;Swift
func executeUpdate(_ sql: String, values: [Any]?) throwsParameters
sqlThe SQL to be performed, with optional
?placeholders.valuesA
NSArrayof objects to be used when binding values to the?placeholders in the SQL statement.errorA
NSErrorobject to receive any error object (if any).Return Value
YESupon success;NOupon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure. -
Execute single update statement
This method executes a single SQL update statement (i.e. any SQL that does not return results, such as
UPDATE,INSERT, orDELETE. This method employssqlite3_prepare_v2andsqlite_stepto perform the update. Unlike the otherexecuteUpdatemethods, this uses printf-style formatters (e.g.%s,%d, etc.) to build the SQL.The optional values provided to this method should be objects (e.g.
NSString,NSNumber,NSNull,NSDate, andNSDataobjects), not fundamental data types (e.g.int,long,NSInteger, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object’sdescriptionmethod.See
lastError
See
lastErrorCode
See
lastErrorMessage
Declaration
Objective-C
- (BOOL)executeUpdate:(nonnull NSString *)sql withParameterDictionary:(nonnull NSDictionary *)arguments;Swift
func executeUpdate(_ sql: String, withParameterDictionary arguments: [AnyHashable : Any]) -> BoolParameters
sqlThe SQL to be performed, with optional
?placeholders.argumentsA
NSDictionaryof objects keyed by column names that will be used when binding values to the?placeholders in the SQL statement.Return Value
YESupon success;NOupon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure. -
Execute single update statement
This method executes a single SQL update statement (i.e. any SQL that does not return results, such as
UPDATE,INSERT, orDELETE. This method employssqlite3_prepare_v2andsqlite_stepto perform the update. Unlike the otherexecuteUpdatemethods, this uses printf-style formatters (e.g.%s,%d, etc.) to build the SQL.The optional values provided to this method should be objects (e.g.
NSString,NSNumber,NSNull,NSDate, andNSDataobjects), not fundamental data types (e.g.int,long,NSInteger, etc.). This method automatically handles the aforementioned object types, and all other object types will be interpreted as text values using the object’sdescriptionmethod.See
lastError
See
lastErrorCode
See
lastErrorMessage
Declaration
Objective-C
- (BOOL)executeUpdate:(nonnull NSString *)sql withVAList:(struct __va_list_tag *)args;Swift
func executeUpdate(_ sql: String, withVAList args: CVaListPointer) -> BoolParameters
sqlThe SQL to be performed, with optional
?placeholders.argsA
va_listof arguments.Return Value
YESupon success;NOupon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure. -
Execute multiple SQL statements
This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the
sqlite3command line.dumpcommand). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This usessqlite3_exec.See
executeStatements:withResultBlock:
See
Declaration
Objective-C
- (BOOL)executeStatements:(nonnull NSString *)sql;Swift
func executeStatements(_ sql: String) -> BoolParameters
sqlThe SQL to be performed
Return Value
YESupon success;NOupon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure. -
Execute multiple SQL statements with callback handler
This executes a series of SQL statements that are combined in a single string (e.g. the SQL generated by the
sqlite3command line.dumpcommand). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This usessqlite3_exec.See
executeStatements:
See
Declaration
Objective-C
- (BOOL)executeStatements:(nonnull NSString *)sql withResultBlock:(FMDBExecuteStatementsCallbackBlock _Nullable)block;Swift
func executeStatements(_ sql: String, withResultBlock block: (([AnyHashable : Any]) -> Int32)? = nil) -> BoolParameters
sqlThe SQL to be performed.
blockA block that will be called for any result sets returned by any SQL statements. Note, if you supply this block, it must return integer value, zero upon success (this would be a good opportunity to use
SQLITE_OK), non-zero value upon failure (which will stop the bulk execution of the SQL). If a statement returns values, the block will be called with the results from the query in NSDictionary *resultsDictionary. This may benilif you don’t care to receive any results.Return Value
YESupon success;NOupon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure. -
Last insert rowid
Each entry in an SQLite table has a unique 64-bit signed integer key called the “rowid”. The rowid is always available as an undeclared column named
ROWID,OID, or_ROWID_as long as those names are not also used by explicitly declared columns. If the table has a column of typeINTEGER PRIMARY KEYthen that column is another alias for the rowid.This routine returns the rowid of the most recent successful
INSERTinto the database from the database connection in the first argument. As of SQLite version 3.7.7, this routines records the last insert rowid of both ordinary tables and virtual tables. If no successfulINSERTstatements have ever occurred on that database connection, zero is returned.Declaration
Objective-C
@property (nonatomic, readonly) int64_t lastInsertRowId;Swift
var lastInsertRowId: Int64 { get }Return Value
The rowid of the last inserted row.
-
The number of rows changed by prior SQL statement.
This function returns the number of database rows that were changed or inserted or deleted by the most recently completed SQL statement on the database connection specified by the first parameter. Only changes that are directly specified by the
INSERT,UPDATE, orDELETEstatement are counted.Declaration
Objective-C
@property (nonatomic, readonly) int changes;Swift
var changes: Int32 { get }Return Value
The number of rows changed by prior SQL statement.
-
Execute select statement
Executing queries returns an
FMResultSetobject if successful, andnilupon failure. Like executing updates, there is a variant that accepts anNSError **parameter. Otherwise you should use thelastErrorMessageandlastErrorMessagemethods to determine why a query failed.In order to iterate through the results of your query, you use a
while()loop. You also need to “step” (via<[FMResultSet next]>) from one record to the other.This method employs
sqlite3_bindfor any optional value parameters. This properly escapes any characters that need escape sequences (e.g. quotation marks), which eliminates simple SQL errors as well as protects against SQL injection attacks. This method natively handlesNSString,NSNumber,NSNull,NSDate, andNSDataobjects. All other object types will be interpreted as text values using the object’sdescriptionmethod.See
FMResultSet
See
See
Note
You cannot use this method from Swift due to incompatibilities between Swift and Objective-C variadic implementations. Consider using
<executeQuery:values:>instead.Declaration
Objective-C
- (FMResultSet *_Nullable)executeQuery:(nonnull NSString *)sql, ...;Parameters
sqlThe SELECT statement to be performed, with optional
?placeholders, followed by optional parameters to bind to?placeholders in the SQL statement. These should be Objective-C objects (e.g.NSString,NSNumber, etc.), not fundamental C data types (e.g.int, etc.).Return Value
A
FMResultSetfor the result set upon success;nilupon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure. -
Execute select statement
Executing queries returns an
FMResultSetobject if successful, andnilupon failure. Like executing updates, there is a variant that accepts anNSError **parameter. Otherwise you should use thelastErrorMessageandlastErrorMessagemethods to determine why a query failed.In order to iterate through the results of your query, you use a
while()loop. You also need to “step” (via<[FMResultSet next]>) from one record to the other.See
executeQuery:
See
FMResultSet
See
Note
This method does not technically perform a traditional printf-style replacement. What this method actually does is replace the printf-style percent sequences with a SQLite
?placeholder, and then bind values to that placeholder. Thus the following command[db executeQueryWithFormat:@"SELECT * FROM test WHERE name=%@", @"Gus"];is actually replacing the
%@with?placeholder, and then performing something equivalent to<executeQuery:>[db executeQuery:@"SELECT * FROM test WHERE name=?", @"Gus"];There are two reasons why this distinction is important. First, the printf-style escape sequences can only be used where it is permissible to use a SQLite
?placeholder. You can use it only for values in SQL statements, but not for table names or column names or any other non-value context. This method also cannot be used in conjunction withpragmastatements and the like. Second, note the lack of quotation marks in the SQL. TheWHEREclause was notWHERE name='%@'(like you might have to do if you built a SQL statement usingNSStringmethodstringWithFormat), but rather simplyWHERE name=%@.Declaration
Objective-C
- (FMResultSet *_Nullable)executeQueryWithFormat:(nonnull NSString *)format, ...;Parameters
formatThe SQL to be performed, with
printf-style escape sequences, followed by ptional parameters to bind to use in conjunction with theprintf-style escape sequences in the SQL statement.Return Value
A
FMResultSetfor the result set upon success;nilupon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure. -
Execute select statement
Executing queries returns an
FMResultSetobject if successful, andnilupon failure. Like executing updates, there is a variant that accepts anNSError **parameter. Otherwise you should use thelastErrorMessageandlastErrorMessagemethods to determine why a query failed.In order to iterate through the results of your query, you use a
while()loop. You also need to “step” (via<[FMResultSet next]>) from one record to the other.See
-executeQuery:values:error:
See
FMResultSet
See
Declaration
Objective-C
- (FMResultSet *_Nullable)executeQuery:(nonnull NSString *)sql withArgumentsInArray:(nonnull NSArray *)arguments;Swift
func executeQuery(_ sql: String, withArgumentsIn arguments: [Any]) -> FMResultSet?Parameters
sqlThe SELECT statement to be performed, with optional
?placeholders.argumentsA
NSArrayof objects to be used when binding values to the?placeholders in the SQL statement.Return Value
A
FMResultSetfor the result set upon success;nilupon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure. -
Execute select statement
Executing queries returns an
FMResultSetobject if successful, andnilupon failure. Like executing updates, there is a variant that accepts anNSError **parameter. Otherwise you should use thelastErrorMessageandlastErrorMessagemethods to determine why a query failed.In order to iterate through the results of your query, you use a
while()loop. You also need to “step” (via<[FMResultSet next]>) from one record to the other.This is similar to
<executeQuery:withArgumentsInArray:>, except that this also accepts a pointer to aNSErrorpointer, so that errors can be returned.In Swift, this throws errors, as if it were defined as follows:
func executeQuery(sql: String, values: [Any]?) throws -> FMResultSet!See
FMResultSet
See
Note
When called from Swift, only use the first two parameters,
sqlandvalues. This but throws the error.Declaration
Objective-C
- (FMResultSet *_Nullable)executeQuery:(nonnull NSString *)sql values:(NSArray *_Nullable)values error:(NSError *_Nullable *_Nullable)error;Swift
func executeQuery(_ sql: String, values: [Any]?) throws -> FMResultSetParameters
sqlThe SELECT statement to be performed, with optional
?placeholders.valuesA
NSArrayof objects to be used when binding values to the?placeholders in the SQL statement.errorA
NSErrorobject to receive any error object (if any).Return Value
A
FMResultSetfor the result set upon success;nilupon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure. -
Execute select statement
Executing queries returns an
FMResultSetobject if successful, andnilupon failure. Like executing updates, there is a variant that accepts anNSError **parameter. Otherwise you should use thelastErrorMessageandlastErrorMessagemethods to determine why a query failed.In order to iterate through the results of your query, you use a
while()loop. You also need to “step” (via<[FMResultSet next]>) from one record to the other.See
FMResultSet
See
Declaration
Objective-C
- (FMResultSet *_Nullable)executeQuery:(nonnull NSString *)sql withParameterDictionary:(NSDictionary *_Nullable)arguments;Swift
func executeQuery(_ sql: String, withParameterDictionary arguments: [AnyHashable : Any]?) -> FMResultSet?Parameters
sqlThe SELECT statement to be performed, with optional
?placeholders.argumentsA
NSDictionaryof objects keyed by column names that will be used when binding values to the?placeholders in the SQL statement.Return Value
A
FMResultSetfor the result set upon success;nilupon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure. -
Undocumented
Declaration
Objective-C
- (FMResultSet * _Nullable)executeQuery:(NSString *)sql withVAList:(va_list)args;Swift
func executeQuery(_ sql: String, withVAList args: CVaListPointer) -> FMResultSet? -
Prepare SQL statement.
Declaration
Objective-C
- (nonnull FMResultSet *)prepare:(nonnull NSString *)sql;Swift
func prepare(_ sql: String) -> FMResultSetParameters
sqlSQL statement to prepare, generally with
?placeholders.
-
Begin a transaction
See
commit
See
rollback
See
beginDeferredTransaction
See
isInTransaction
Warning
Unlike SQLite’s
BEGIN TRANSACTION, this method currently performs an exclusive transaction, not a deferred transaction. This behavior is likely to change in future versions of FMDB, whereby this method will likely eventually adopt standard SQLite behavior and perform deferred transactions. If you really need exclusive tranaction, it is recommended that you usebeginExclusiveTransaction,instead, not only to make your intent explicit, but also to future-proof your code.Declaration
Objective-C
- (BOOL)beginTransaction;Swift
func beginTransaction() -> BoolReturn Value
YESon success;NOon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure. -
Begin a deferred transaction
See
commit
See
rollback
See
beginTransaction
See
isInTransaction
Declaration
Objective-C
- (BOOL)beginDeferredTransaction;Swift
func beginDeferredTransaction() -> BoolReturn Value
YESon success;NOon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure. -
Begin an immediate transaction
See
commit
See
rollback
See
beginTransaction
See
isInTransaction
Declaration
Objective-C
- (BOOL)beginImmediateTransaction;Swift
func beginImmediateTransaction() -> BoolReturn Value
YESon success;NOon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure. -
Begin an exclusive transaction
See
commit
See
rollback
See
beginTransaction
See
isInTransaction
Declaration
Objective-C
- (BOOL)beginExclusiveTransaction;Swift
func beginExclusiveTransaction() -> BoolReturn Value
YESon success;NOon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure. -
Commit a transaction
Commit a transaction that was initiated with either
<beginTransaction>or with<beginDeferredTransaction>.See
beginTransaction
See
beginDeferredTransaction
See
rollback
See
isInTransaction
Declaration
Objective-C
- (BOOL)commit;Swift
func commit() -> BoolReturn Value
YESon success;NOon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure. -
Rollback a transaction
Rollback a transaction that was initiated with either
<beginTransaction>or with<beginDeferredTransaction>.See
beginTransaction
See
beginDeferredTransaction
See
commit
See
isInTransaction
Declaration
Objective-C
- (BOOL)rollback;Swift
func rollback() -> BoolReturn Value
YESon success;NOon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure. -
Identify whether currently in a transaction or not
See
beginTransactionSee
beginDeferredTransactionSee
commitSee
rollbackDeclaration
Objective-C
@property (nonatomic, readonly) BOOL isInTransaction;Swift
var isInTransaction: Bool { get } -
Deprecated
Use isInTransaction property instead
Undocumented
Declaration
Objective-C
- (BOOL)inTransaction __deprecated_msg("Use isInTransaction property instead");Swift
func inTransaction() -> Bool
-
Clear cached statements
Declaration
Objective-C
- (void)clearCachedStatements;Swift
func clearCachedStatements() -
Close all open result sets
Declaration
Objective-C
- (void)closeOpenResultSets;Swift
func closeOpenResultSets() -
Whether database has any open result sets
Declaration
Objective-C
@property (nonatomic, readonly) BOOL hasOpenResultSets;Swift
var hasOpenResultSets: Bool { get }Return Value
YESif there are open result sets;NOif not. -
Whether should cache statements or not
Declaration
Objective-C
@property (nonatomic) BOOL shouldCacheStatements;Swift
var shouldCacheStatements: Bool { get set } -
Interupt pending database operation
This method causes any pending database operation to abort and return at its earliest opportunity
Declaration
Objective-C
- (BOOL)interrupt;Swift
func interrupt() -> BoolReturn Value
YESon success;NOon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure.
-
Set encryption key.
Warning
You need to have purchased the sqlite encryption extensions for this method to work.
Declaration
Objective-C
- (BOOL)setKey:(nonnull NSString *)key;Swift
func setKey(_ key: String) -> BoolParameters
keyThe key to be used.
Return Value
YESif success,NOon error. -
Reset encryption key
Warning
You need to have purchased the sqlite encryption extensions for this method to work.
Declaration
Objective-C
- (BOOL)rekey:(nonnull NSString *)key;Swift
func rekey(_ key: String) -> BoolParameters
keyThe key to be used.
Return Value
YESif success,NOon error. -
Set encryption key using
keyData.Warning
You need to have purchased the sqlite encryption extensions for this method to work.
Declaration
Objective-C
- (BOOL)setKeyWithData:(nonnull NSData *)keyData;Swift
func setKeyWith(_ keyData: Data) -> BoolParameters
keyDataThe
NSDatato be used.Return Value
YESif success,NOon error. -
Reset encryption key using
keyData.Warning
You need to have purchased the sqlite encryption extensions for this method to work.
Declaration
Objective-C
- (BOOL)rekeyWithData:(nonnull NSData *)keyData;Swift
func rekey(with keyData: Data) -> BoolParameters
keyDataThe
NSDatato be used.Return Value
YESif success,NOon error.
-
The path of the database file.
Declaration
Objective-C
@property (nonatomic, readonly, nullable) NSString *databasePath;Swift
var databasePath: String? { get } -
The file URL of the database file.
Declaration
Objective-C
@property (nonatomic, readonly, nullable) NSURL *databaseURL;Swift
var databaseURL: URL? { get } -
The underlying SQLite handle .
Declaration
Objective-C
@property (nonatomic, readonly) void *_Nonnull sqliteHandle;Swift
var sqliteHandle: UnsafeMutableRawPointer { get }Return Value
The
sqlite3pointer.
-
Last error message
Returns the English-language text that describes the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined.
See
See
lastErrorCode
See
lastError
Declaration
Objective-C
- (nonnull NSString *)lastErrorMessage;Swift
func lastErrorMessage() -> StringReturn Value
NSStringof the last error message. -
Last error code
Returns the numeric result code or extended result code for the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined.
See
lastErrorMessage
See
lastError
Declaration
Objective-C
- (int)lastErrorCode;Swift
func lastErrorCode() -> Int32Return Value
Integer value of the last error code.
-
Last extended error code
Returns the numeric extended result code for the most recent failed SQLite API call associated with a database connection. If a prior API call failed but the most recent API call succeeded, this return value is undefined.
See
lastErrorMessage
See
lastError
Declaration
Objective-C
- (int)lastExtendedErrorCode;Swift
func lastExtendedErrorCode() -> Int32Return Value
Integer value of the last extended error code.
-
Had error
See
lastError
See
lastErrorCode
See
lastErrorMessage
Declaration
Objective-C
- (BOOL)hadError;Swift
func hadError() -> BoolReturn Value
YESif there was an error,NOif no error. -
Last error
See
lastErrorCode
See
lastErrorMessage
Declaration
Objective-C
- (nonnull NSError *)lastError;Swift
func lastError() -> ErrorReturn Value
NSErrorrepresenting the last error. -
Undocumented
Declaration
Objective-C
@property (nonatomic) NSTimeInterval maxBusyRetryTimeIntervalSwift
var maxBusyRetryTimeInterval: TimeInterval { get set }
-
Start save point
See
releaseSavePointWithName:error:
See
rollbackToSavePointWithName:error:
Declaration
Objective-C
- (BOOL)startSavePointWithName:(nonnull NSString *)name error:(NSError *_Nullable *_Nullable)outErr;Swift
func startSavePoint(withName name: String) throwsParameters
nameName of save point.
outErrA
NSErrorobject to receive any error object (if any).Return Value
YESon success;NOon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure. -
Release save point
See
startSavePointWithName:error:
See
rollbackToSavePointWithName:error:
Declaration
Objective-C
- (BOOL)releaseSavePointWithName:(nonnull NSString *)name error:(NSError *_Nullable *_Nullable)outErr;Swift
func releaseSavePoint(withName name: String) throwsParameters
nameName of save point.
outErrA
NSErrorobject to receive any error object (if any).Return Value
YESon success;NOon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure. -
Roll back to save point
See
startSavePointWithName:error:
See
releaseSavePointWithName:error:
Declaration
Objective-C
- (BOOL)rollbackToSavePointWithName:(nonnull NSString *)name error:(NSError *_Nullable *_Nullable)outErr;Swift
func rollbackToSavePoint(withName name: String) throwsParameters
nameName of save point.
outErrA
NSErrorobject to receive any error object (if any).Return Value
YESon success;NOon failure. If failed, you can calllastError,lastErrorCode, orlastErrorMessagefor diagnostic information regarding the failure. -
Start save point
See
startSavePointWithName:error:
See
releaseSavePointWithName:error:
See
rollbackToSavePointWithName:error:
Declaration
Objective-C
- (NSError *_Nullable)inSavePoint:(nonnull void (^)(BOOL *_Nonnull))block;Swift
func inSavePoint(_ block: (UnsafeMutablePointer<ObjCBool>) -> Void) -> Error?Parameters
blockBlock of code to perform from within save point.
Return Value
The NSError corresponding to the error, if any. If no error, returns
nil.
-
Performs a WAL checkpoint
Declaration
Objective-C
- (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode error:(NSError *_Nullable *_Nullable)error;Swift
func checkpoint(_ checkpointMode: FMDBCheckpointMode) throwsParameters
checkpointModeThe checkpoint mode for
sqlite3_wal_checkpoint_v2errorThe
NSErrorcorresponding to the error, if any.Return Value
YESon success, otherwiseNO. -
Performs a WAL checkpoint
Declaration
Objective-C
- (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode name:(NSString *_Nullable)name error:(NSError *_Nullable *_Nullable)error;Swift
func checkpoint(_ checkpointMode: FMDBCheckpointMode, name: String?) throwsParameters
checkpointModeThe checkpoint mode for
sqlite3_wal_checkpoint_v2nameThe db name for
sqlite3_wal_checkpoint_v2errorThe
NSErrorcorresponding to the error, if any.Return Value
YESon success, otherwiseNO. -
Performs a WAL checkpoint
Declaration
Objective-C
- (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode name:(NSString *_Nullable)name logFrameCount:(int *_Nullable)logFrameCount checkpointCount:(int *_Nullable)checkpointCount error:(NSError *_Nullable *_Nullable)error;Swift
func checkpoint(_ checkpointMode: FMDBCheckpointMode, name: String?, logFrameCount: UnsafeMutablePointer<Int32>?, checkpointCount: UnsafeMutablePointer<Int32>?) throwsParameters
checkpointModeThe checkpoint mode for sqlite3_wal_checkpoint_v2
nameThe db name for sqlite3_wal_checkpoint_v2
errorThe NSError corresponding to the error, if any.
logFrameCountIf not
NULL, then this is set to the total number of frames in the log file or to -1 if the checkpoint could not run because of an error or because the database is not in WAL mode.checkpointCountIf not
NULL, then this is set to the total number of checkpointed frames in the log file (including any that were already checkpointed before the function was called) or to -1 if the checkpoint could not run due to an error or because the database is not in WAL mode.Return Value
YESon success, otherwiseNO.
-
Test to see if the library is threadsafe
Declaration
Objective-C
+ (BOOL)isSQLiteThreadSafe;Swift
class func isSQLiteThreadSafe() -> BoolReturn Value
NOif and only if SQLite was compiled with mutexing code omitted due to theSQLITE_THREADSAFEcompile-time option being set to 0. -
Examine/set limits
See
Declaration
Objective-C
- (int)limitFor:(int)type value:(int)newLimit;Swift
func limit(for type: Int32, value newLimit: Int32) -> Int32Parameters
typeThe type of limit. See https://sqlite.org/c3ref/c_limit_attached.html
newLimitThe new limit value. Use -1 if you don’t want to change the limit, but rather only want to check it.
Return Value
Regardless, returns previous value.
-
Run-time library version numbers
Declaration
Objective-C
+ (nonnull NSString *)sqliteLibVersion;Swift
class func sqliteLibVersion() -> StringReturn Value
The sqlite library version string.
-
The FMDB version number as a string in the form of
"2.7.7".If you want to compare version number strings, you can use NSNumericSearch option:
NSComparisonResult result = [[FMDatabase FMDBUserVersion] compare:@"2.11.0" options:NSNumericSearch];@returns The version number string.
Declaration
Objective-C
+ (nonnull NSString *)FMDBUserVersion;Swift
class func fmdbUserVersion() -> String -
Deprecated
Use FMDBUserVersion instead
The FMDB version
This returns the FMDB as hexadecimal value, e.g.,
0x0243for version 2.4.3.Warning
This routine will not work if any component of the version number exceeds 15. For example, if it is version2.17.3, this will max out at0x2f3.For this reason, we would recommend usingFMDBUserVersionand withNSNumericSearchoption, e.g.NSComparisonResult result = [[FMDatabase FMDBUserVersion] compare:@"2.11.0" options:NSNumericSearch];@returns The version number in hexadecimal, e.g.,
0x0243for version 2.4.3. If any component exceeds what can be can be represented in four bits, we’ll max it out at0xf.Declaration
Objective-C
+ (SInt32)FMDBVersion;Swift
class func fmdbVersion() -> Int32
-
Adds SQL functions or aggregates or to redefine the behavior of existing SQL functions or aggregates.
For example:
[db makeFunctionNamed:@"RemoveDiacritics" arguments:1 block:^(void *context, int argc, void **argv) { SqliteValueType type = [self.db valueType:argv[0]]; if (type == SqliteValueTypeNull) { [self.db resultNullInContext:context]; return; } if (type != SqliteValueTypeText) { [self.db resultError:@"Expected text" context:context]; return; } NSString *string = [self.db valueString:argv[0]]; NSString *result = [string stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:nil]; [self.db resultString:result context:context]; }]; FMResultSet *rs = [db executeQuery:@"SELECT * FROM employees WHERE RemoveDiacritics(first_name) LIKE 'jose'"]; NSAssert(rs, @"Error %@", [db lastErrorMessage]);Declaration
Objective-C
- (void)makeFunctionNamed:(nonnull NSString *)name arguments:(int)arguments block:(nonnull void (^)(void *_Nonnull, int, void *_Nonnull *_Nonnull))block;Swift
func makeFunctionNamed(_ name: String, arguments: Int32, block: @escaping (UnsafeMutableRawPointer, Int32, UnsafeMutablePointer<UnsafeMutableRawPointer>) -> Void)Parameters
nameName of function.
argumentsMaximum number of parameters.
blockThe block of code for the function.
-
Deprecated
Use makeFunctionNamed:arguments:block:
Undocumented
Declaration
Objective-C
- (void)makeFunctionNamed:(NSString *)name maximumArguments:(int)count withBlock:(void (^)(void *context, int argc, void * _Nonnull * _Nonnull argv))block __deprecated_msg("Use makeFunctionNamed:arguments:block:");Swift
func makeFunctionNamed(_ name: String, maximumArguments count: Int32, with block: @escaping (UnsafeMutableRawPointer, Int32, UnsafeMutablePointer<UnsafeMutableRawPointer>) -> Void) -
Undocumented
Declaration
Objective-C
- (SqliteValueType)valueType:(void *)argv;Swift
func valueType(_ argv: UnsafeMutableRawPointer) -> SqliteValueType -
Get integer value of parameter in custom function.
See
makeFunctionNamed:arguments:block:
Declaration
Objective-C
- (int)valueInt:(nonnull void *)value;Swift
func valueInt(_ value: UnsafeMutableRawPointer) -> Int32Parameters
valueThe argument whose value to return.
Return Value
The integer value.
-
Get long value of parameter in custom function.
See
makeFunctionNamed:arguments:block:
Declaration
Objective-C
- (long long)valueLong:(nonnull void *)value;Swift
func valueLong(_ value: UnsafeMutableRawPointer) -> Int64Parameters
valueThe argument whose value to return.
Return Value
The long value.
-
Get double value of parameter in custom function.
See
makeFunctionNamed:arguments:block:
Declaration
Objective-C
- (double)valueDouble:(nonnull void *)value;Swift
func valueDouble(_ value: UnsafeMutableRawPointer) -> DoubleParameters
valueThe argument whose value to return.
Return Value
The double value.
-
Get
NSDatavalue of parameter in custom function.See
makeFunctionNamed:arguments:block:
Declaration
Objective-C
- (NSData *_Nullable)valueData:(nonnull void *)value;Swift
func valueData(_ value: UnsafeMutableRawPointer) -> Data?Parameters
valueThe argument whose value to return.
Return Value
The data object.
-
Get string value of parameter in custom function.
See
makeFunctionNamed:arguments:block:
Declaration
Objective-C
- (NSString *_Nullable)valueString:(nonnull void *)value;Swift
func valueString(_ value: UnsafeMutableRawPointer) -> String?Parameters
valueThe argument whose value to return.
Return Value
The string value.
-
Return null value from custom function.
See
makeFunctionNamed:arguments:block:
Declaration
Objective-C
- (void)resultNullInContext:(nonnull void *)context;Swift
func resultNull(context: UnsafeMutableRawPointer)Parameters
contextThe context to which the null value will be returned.
-
Return integer value from custom function.
See
makeFunctionNamed:arguments:block:
Declaration
Objective-C
- (void)resultInt:(int)value context:(nonnull void *)context;Swift
func resultInt(_ value: Int32, context: UnsafeMutableRawPointer)Parameters
valueThe integer value to be returned.
contextThe context to which the value will be returned.
-
Return long value from custom function.
See
makeFunctionNamed:arguments:block:
Declaration
Objective-C
- (void)resultLong:(long long)value context:(nonnull void *)context;Swift
func resultLong(_ value: Int64, context: UnsafeMutableRawPointer)Parameters
valueThe long value to be returned.
contextThe context to which the value will be returned.
-
Return double value from custom function.
See
makeFunctionNamed:arguments:block:
Declaration
Objective-C
- (void)resultDouble:(double)value context:(nonnull void *)context;Swift
func resultDouble(_ value: Double, context: UnsafeMutableRawPointer)Parameters
valueThe double value to be returned.
contextThe context to which the value will be returned.
-
Return
NSDataobject from custom function.See
makeFunctionNamed:arguments:block:
Declaration
Objective-C
- (void)resultData:(nonnull NSData *)data context:(nonnull void *)context;Swift
func resultData(_ data: Data, context: UnsafeMutableRawPointer)Parameters
dataThe
NSDataobject to be returned.contextThe context to which the value will be returned.
-
Return string value from custom function.
See
makeFunctionNamed:arguments:block:
Declaration
Objective-C
- (void)resultString:(nonnull NSString *)value context:(nonnull void *)context;Swift
func resultString(_ value: String, context: UnsafeMutableRawPointer)Parameters
valueThe string value to be returned.
contextThe context to which the value will be returned.
-
Return error string from custom function.
See
makeFunctionNamed:arguments:block:
Declaration
Objective-C
- (void)resultError:(nonnull NSString *)error context:(nonnull void *)context;Swift
func resultError(_ error: String, context: UnsafeMutableRawPointer)Parameters
errorThe error string to be returned.
contextThe context to which the error will be returned.
-
Return error code from custom function.
See
makeFunctionNamed:arguments:block:
Declaration
Objective-C
- (void)resultErrorCode:(int)errorCode context:(nonnull void *)context;Swift
func resultErrorCode(_ errorCode: Int32, context: UnsafeMutableRawPointer)Parameters
errorCodeThe integer error code to be returned.
contextThe context to which the error will be returned.
-
Report memory error in custom function.
See
makeFunctionNamed:arguments:block:
Declaration
Objective-C
- (void)resultErrorNoMemoryInContext:(nonnull void *)context;Swift
func resultErrorNoMemory(context: UnsafeMutableRawPointer)Parameters
contextThe context to which the error will be returned.
-
Report that string or BLOB is too long to represent in custom function.
See
makeFunctionNamed:arguments:block:
Declaration
Objective-C
- (void)resultErrorTooBigInContext:(nonnull void *)context;Swift
func resultErrorTooBig(context: UnsafeMutableRawPointer)Parameters
contextThe context to which the error will be returned.
-
Generate an
NSDateFormatterthat won’t be broken by permutations of timezones or locales.Use this method to generate values to set the dateFormat property.
Example:
myDB.dateFormat = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"];See
hasDateFormatter
See
setDateFormat:
See
dateFromString:
See
stringFromDate:
See
storeableDateFormat:
Warning
Note that
NSDateFormatteris not thread-safe, so the formatter generated by this method should be assigned to only one FMDB instance and should not be used for other purposes.Declaration
Objective-C
+ (nonnull NSDateFormatter *)storeableDateFormat:(nonnull NSString *)format;Swift
class func storeableDateFormat(_ format: String) -> DateFormatterParameters
formatA valid NSDateFormatter format string.
Return Value
A
NSDateFormatterthat can be used for converting dates to strings and vice versa. -
Test whether the database has a date formatter assigned.
See
hasDateFormatter
See
setDateFormat:
See
dateFromString:
See
stringFromDate:
See
storeableDateFormat:
Declaration
Objective-C
- (BOOL)hasDateFormatter;Swift
func hasDateFormatter() -> BoolReturn Value
YESif there is a date formatter;NOif not. -
Set to a date formatter to use string dates with sqlite instead of the default UNIX timestamps.
See
hasDateFormatter
See
setDateFormat:
See
dateFromString:
See
stringFromDate:
See
storeableDateFormat:
Warning
Note there is no direct getter for the
NSDateFormatter, and you should not use the formatter you pass to FMDB for other purposes, asNSDateFormatteris not thread-safe.Declaration
Objective-C
- (void)setDateFormat:(NSDateFormatter *_Nullable)format;Swift
func setDateFormat(_ format: DateFormatter?)Parameters
formatSet to nil to use UNIX timestamps. Defaults to nil. Should be set using a formatter generated using
FMDatabase:storeableDateFormat. -
Convert the supplied NSString to NSDate, using the current database formatter.
See
hasDateFormatter
See
setDateFormat:
See
dateFromString:
See
stringFromDate:
See
storeableDateFormat:
Declaration
Objective-C
- (NSDate *_Nullable)dateFromString:(nonnull NSString *)s;Swift
func date(from s: String) -> Date?Parameters
sNSStringto convert toNSDate.Return Value
The
NSDateobject; ornilif no formatter is set. -
Convert the supplied NSDate to NSString, using the current database formatter.
See
hasDateFormatter
See
setDateFormat:
See
dateFromString:
See
stringFromDate:
See
storeableDateFormat:
Declaration
Objective-C
- (NSString *_Nullable)stringFromDate:(nonnull NSDate *)date;Swift
func string(from date: Date) -> String?Parameters
dateNSDateof date to convert toNSString.Return Value
The
NSStringrepresentation of the date;nilif no formatter is set.
-
Return
intvalue for queryNote
This is not available from Swift.
Declaration
Objective-C
- (int)intForQuery:(nonnull NSString *)query, ...;Parameters
queryThe SQL query to be performed, followed by a list of parameters that will be bound to the
?placeholders in the SQL query.Return Value
intvalue. -
Return
longvalue for queryNote
This is not available from Swift.
Declaration
Objective-C
- (long)longForQuery:(nonnull NSString *)query, ...;Parameters
queryThe SQL query to be performed, followed by a list of parameters that will be bound to the
?placeholders in the SQL query.Return Value
longvalue. -
Return
BOOLvalue for queryNote
This is not available from Swift.
Declaration
Objective-C
- (BOOL)boolForQuery:(nonnull NSString *)query, ...;Parameters
queryThe SQL query to be performed, followed by a list of parameters that will be bound to the
?placeholders in the SQL query.Return Value
BOOLvalue. -
Return
doublevalue for queryNote
This is not available from Swift.
Declaration
Objective-C
- (double)doubleForQuery:(nonnull NSString *)query, ...;Parameters
queryThe SQL query to be performed, followed by a list of parameters that will be bound to the
?placeholders in the SQL query.Return Value
doublevalue. -
Return
NSStringvalue for queryNote
This is not available from Swift.
Declaration
Objective-C
- (NSString *_Nullable)stringForQuery:(nonnull NSString *)query, ...;Parameters
queryThe SQL query to be performed, followed by a list of parameters that will be bound to the
?placeholders in the SQL query.Return Value
NSStringvalue. -
Return
NSDatavalue for queryNote
This is not available from Swift.
Declaration
Objective-C
- (NSData *_Nullable)dataForQuery:(nonnull NSString *)query, ...;Parameters
queryThe SQL query to be performed, followed by a list of parameters that will be bound to the
?placeholders in the SQL query.Return Value
NSDatavalue. -
Return
NSDatevalue for queryNote
This is not available from Swift.
Declaration
Objective-C
- (NSDate *_Nullable)dateForQuery:(nonnull NSString *)query, ...;Parameters
queryThe SQL query to be performed, followed by a list of parameters that will be bound to the
?placeholders in the SQL query.Return Value
NSDatevalue.
-
Does table exist in database?
Declaration
Objective-C
- (BOOL)tableExists:(nonnull NSString *)tableName;Swift
func tableExists(_ tableName: String) -> BoolParameters
tableNameThe name of the table being looked for.
Return Value
YESif table found;NOif not found. -
The schema of the database.
This will be the schema for the entire database. For each entity, each row of the result set will include the following fields:
type- The type of entity (e.g. table, index, view, or trigger)name- The name of the objecttbl_name- The name of the table to which the object referencesrootpage- The page number of the root b-tree page for tables and indicessql- The SQL that created the entity
Return Value
FMResultSetof schema;nilon error. -
The schema of the database.
This will be the schema for a particular table as report by SQLite
PRAGMA, for example:PRAGMA table_info('employees')This will report:
cid- The column ID numbername- The name of the columntype- The data type specified for the columnnotnull- whether the field is defined as NOT NULL (i.e. values required)dflt_value- The default value for the columnpk- Whether the field is part of the primary key of the table
See
Declaration
Objective-C
- (FMResultSet *_Nullable)getTableSchema:(nonnull NSString *)tableName;Swift
func getTableSchema(_ tableName: String) -> FMResultSet?Parameters
tableNameThe name of the table for whom the schema will be returned.
Return Value
FMResultSetof schema;nilon error. -
Test to see if particular column exists for particular table in database
Declaration
Objective-C
- (BOOL)columnExists:(nonnull NSString *)columnName inTableWithName:(nonnull NSString *)tableName;Swift
func columnExists(_ columnName: String, inTableWithName tableName: String) -> BoolParameters
columnNameThe name of the column.
tableNameThe name of the table.
Return Value
YESif column exists in table in question;NOotherwise. -
Deprecated
Use columnExists:inTableWithName: instead
Test to see if particular column exists for particular table in database
See
columnExists:inTableWithName:
Warning
Deprecated - use
<columnExists:inTableWithName:>instead.Declaration
Objective-C
- (BOOL)columnExists:(nonnull NSString *)tableName columnName:(nonnull NSString *)columnName;Swift
func columnExists(_ tableName: String, columnName: String) -> BoolParameters
columnNameThe name of the column.
tableNameThe name of the table.
Return Value
YESif column exists in table in question;NOotherwise. -
Validate SQL statement
This validates SQL statement by performing
sqlite3_prepare_v2, but not returning the results, but instead immediately callingsqlite3_finalize.Declaration
Objective-C
- (BOOL)validateSQL:(nonnull NSString *)sql error:(NSError *_Nullable *_Nullable)error;Swift
func validateSQL(_ sql: String) throwsParameters
sqlThe SQL statement being validated.
errorThis is a pointer to a
NSErrorobject that will receive the autoreleasedNSErrorobject if there was any error. If this isnil, noNSErrorresult will be returned.Return Value
YESif validation succeeded without incident;NOotherwise.
-
Retrieve application ID
See
setApplicationID:
Declaration
Objective-C
@property (nonatomic) uint32_t applicationID;Swift
var applicationID: UInt32 { get set }Return Value
The
uint32_tnumeric value of the application ID. -
Retrieve application ID string
See
setApplicationIDString:Declaration
Objective-C
@property (nonatomic, retain) NSString *_Nonnull applicationIDString;Swift
var applicationIDString: String { get set }
-
Retrieve user version
See
setUserVersion:Declaration
Objective-C
@property (nonatomic) uint32_t userVersion;Swift
var userVersion: UInt32 { get set }
View on GitHub
FMDatabase Class Reference