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 an FMDatabase .

  • FMDatabaseQueue - If you want to perform queries and updates on multiple threads, you’ll want to use this class.

See also

External links

Warning

Do not instantiate a single FMDatabase object and use it across multiple threads. Instead, use FMDatabaseQueue .

Properties

  • 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 }

Initialization

  • Create a FMDatabase object.

    An FMDatabase is created with a path to a SQLite database file. This path can be one of these three:

    1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you.

    2. An zero-length string. An empty database is created at a temporary location. This database is deleted with the FMDatabase connection is closed.

    3. nil . An in-memory database is created. This database will be destroyed with the FMDatabase connection 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

    inPath

    Path of database file

    Return Value

    FMDatabase object if successful; nil if failure.

  • Create a FMDatabase object.

    An FMDatabase is created with a path to a SQLite database file. This path can be one of these three:

    1. A file system URL. The file does not have to exist on disk. If it does not exist, it is created for you.

    2. nil . An in-memory database is created. This database will be destroyed with the FMDatabase connection 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

    url

    The local file URL (not remote URL) of database file

    Return Value

    FMDatabase object if successful; nil if failure.

  • Initialize a FMDatabase object.

    An FMDatabase is created with a path to a SQLite database file. This path can be one of these three:

    1. A file system path. The file does not have to exist on disk. If it does not exist, it is created for you.

    2. A zero-length string. An empty database is created at a temporary location. This database is deleted with the FMDatabase connection is closed.

    3. nil . An in-memory database is created. This database will be destroyed with the FMDatabase connection 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

    path

    Path of database file.

    Return Value

    FMDatabase object if successful; nil if failure.

  • Initialize a FMDatabase object.

    An FMDatabase is created with a local file URL to a SQLite database file. This path can be one of these three:

    1. A file system URL. The file does not have to exist on disk. If it does not exist, it is created for you.

    2. nil . An in-memory database is created. This database will be destroyed with the FMDatabase connection 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

    url

    The file NSURL of database file.

    Return Value

    FMDatabase object if successful; nil if failure.

Opening and closing database

  • 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

    openWithFlags:

    See

    close

    Declaration

    Objective-C

    - (BOOL)open;

    Swift

    func open() -> Bool

    Return Value

    YES if successful, NO on error.

  • Opening a new database connection with flags and an optional virtual file system (VFS)

    SQLITE_OPEN_READONLY
    

    The database is opened in read-only mode. If the database does not already exist, an error is returned.

    SQLITE_OPEN_READWRITE
    

    The 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_CREATE
    

    The 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 open method.

    See

    open

    See

    close

    Declaration

    Objective-C

    - (BOOL)openWithFlags:(int)flags;

    Swift

    func open(withFlags flags: Int32) -> Bool

    Parameters

    flags

    One of the following three values, optionally combined with the SQLITE_OPEN_NOMUTEX , SQLITE_OPEN_FULLMUTEX , SQLITE_OPEN_SHAREDCACHE , SQLITE_OPEN_PRIVATECACHE , and/or SQLITE_OPEN_URI flags:

    Return Value

    YES if successful, NO on error.

  • Opening a new database connection with flags and an optional virtual file system (VFS)

    SQLITE_OPEN_READONLY
    

    The database is opened in read-only mode. If the database does not already exist, an error is returned.

    SQLITE_OPEN_READWRITE
    

    The 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_CREATE
    

    The 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 open method.

    See

    open

    See

    close

    Declaration

    Objective-C

    - (BOOL)openWithFlags:(int)flags vfs:(NSString *_Nullable)vfsName;

    Swift

    func open(withFlags flags: Int32, vfs vfsName: String?) -> Bool

    Parameters

    flags

    One of the following three values, optionally combined with the SQLITE_OPEN_NOMUTEX , SQLITE_OPEN_FULLMUTEX, SQLITE_OPEN_SHAREDCACHE, SQLITE_OPEN_PRIVATECACHE , and/or SQLITE_OPEN_URI flags:

    vfsName

    If vfs is given the value is passed to the vfs parameter of sqlite3_open_v2.

    Return Value

    YES if successful, NO on error.

  • Closing a database connection

    See

    open

    See

    openWithFlags:

    Declaration

    Objective-C

    - (BOOL)close;

    Swift

    func close() -> Bool

    Return Value

    YES if success, NO on 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 SELECT statement and confirm that it succeeds.

    Declaration

    Objective-C

    @property (nonatomic, readonly) BOOL goodConnection;

    Swift

    var goodConnection: Bool { get }

    Return Value

    YES if everything succeeds, NO on failure.

Perform updates

  • 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 , or DELETE . This method employs sqlite3_prepare_v2, sqlite3_bind to bind values to ? placeholders in the SQL with the optional list of parameters, and sqlite_step to perform the update.

    The optional values provided to this method should be objects (e.g. NSString , NSNumber , NSNull , NSDate , and NSData objects), 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’s description method.

    See

    lastError

    See

    lastErrorCode

    See

    lastErrorMessage

    Declaration

    Objective-C

    - (BOOL)executeUpdate:(nonnull NSString *)sql
        withErrorAndBindings:(NSError *_Nullable *_Nullable)outErr, ...;

    Parameters

    sql

    The 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.).

    outErr

    A reference to the NSError pointer to be updated with an auto released NSError object if an error if an error occurs. If nil , no NSError object will be returned.

    Return Value

    YES upon success; NO upon failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for 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 , or DELETE . This method employs sqlite3_prepare_v2, sqlite3_bind to bind values to ? placeholders in the SQL with the optional list of parameters, and sqlite_step to perform the update.

    The optional values provided to this method should be objects (e.g. NSString , NSNumber , NSNull , NSDate , and NSData objects), 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’s description method.

    See

    lastError

    See

    lastErrorCode

    See

    lastErrorMessage

    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 using stringWithFormat to 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

    sql

    The 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

    YES upon success; NO upon failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for 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 , or DELETE . This method employs sqlite3_prepare_v2 and sqlite_step to perform the update. Unlike the other executeUpdate methods, 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 with pragma statements and the like. Second, note the lack of quotation marks in the SQL. The VALUES clause was not VALUES ('%@') (like you might have to do if you built a SQL statement using NSString method stringWithFormat ), but rather simply VALUES (%@).

    Declaration

    Objective-C

    - (BOOL)executeUpdateWithFormat:(nonnull NSString *)format, ...;

    Parameters

    format

    The SQL to be performed, with printf-style escape sequences, followed by optional parameters to bind to use in conjunction with the printf-style escape sequences in the SQL statement.

    Return Value

    YES upon success; NO upon failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for 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 , or DELETE . This method employs sqlite3_prepare_v2 and sqlite3_bind binding 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 , and NSData objects), 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’s description method.

    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]) -> Bool

    Parameters

    sql

    The SQL to be performed, with optional ? placeholders.

    arguments

    A NSArray of objects to be used when binding values to the ? placeholders in the SQL statement.

    Return Value

    YES upon success; NO upon failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for 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 , or DELETE . This method employs sqlite3_prepare_v2 and sqlite3_bind binding 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 , and NSData objects), 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’s description method.

    This is similar to executeUpdate:withArgumentsInArray: , except that this also accepts a pointer to a NSError pointer, 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]?) throws

    Parameters

    sql

    The SQL to be performed, with optional ? placeholders.

    values

    A NSArray of objects to be used when binding values to the ? placeholders in the SQL statement.

    error

    A NSError object to receive any error object (if any).

    Return Value

    YES upon success; NO upon failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for 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 , or DELETE . This method employs sqlite3_prepare_v2 and sqlite_step to perform the update. Unlike the other executeUpdate methods, 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 , and NSData objects), 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’s description method.

    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]) -> Bool

    Parameters

    sql

    The SQL to be performed, with optional ? placeholders.

    arguments

    A NSDictionary of objects keyed by column names that will be used when binding values to the ? placeholders in the SQL statement.

    Return Value

    YES upon success; NO upon failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for 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 , or DELETE . This method employs sqlite3_prepare_v2 and sqlite_step to perform the update. Unlike the other executeUpdate methods, 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 , and NSData objects), 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’s description method.

    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) -> Bool

    Parameters

    sql

    The SQL to be performed, with optional ? placeholders.

    args

    A va_list of arguments.

    Return Value

    YES upon success; NO upon failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for 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 sqlite3 command line .dump command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses sqlite3_exec .

    See

    executeStatements:withResultBlock:

    Declaration

    Objective-C

    - (BOOL)executeStatements:(nonnull NSString *)sql;

    Swift

    func executeStatements(_ sql: String) -> Bool

    Parameters

    sql

    The SQL to be performed

    Return Value

    YES upon success; NO upon failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for 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 sqlite3 command line .dump command). This accepts no value parameters, but rather simply expects a single string with multiple SQL statements, each terminated with a semicolon. This uses sqlite3_exec.

    See

    executeStatements:

    Declaration

    Objective-C

    - (BOOL)executeStatements:(nonnull NSString *)sql
              withResultBlock:(FMDBExecuteStatementsCallbackBlock _Nullable)block;

    Swift

    func executeStatements(_ sql: String, withResultBlock block: (([AnyHashable : Any]) -> Int32)? = nil) -> Bool

    Parameters

    sql

    The SQL to be performed.

    block

    A 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 be nil if you don’t care to receive any results.

    Return Value

    YES upon success; NO upon failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for 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 type INTEGER PRIMARY KEY then that column is another alias for the rowid.

    This routine returns the rowid of the most recent successful INSERT into 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 successful INSERT statements 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 , or DELETE statement 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.

Retrieving results

  • Execute select statement

    Executing queries returns an FMResultSet object if successful, and nil upon failure. Like executing updates, there is a variant that accepts an NSError ** parameter. Otherwise you should use the lastErrorMessage and lastErrorMessage methods 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_bind for 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 handles NSString , NSNumber , NSNull , NSDate , and NSData objects. All other object types will be interpreted as text values using the object’s description method.

    See

    FMResultSet

    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

    sql

    The 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 FMResultSet for the result set upon success; nil upon failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for diagnostic information regarding the failure.

  • Execute select statement

    Executing queries returns an FMResultSet object if successful, and nil upon failure. Like executing updates, there is a variant that accepts an NSError ** parameter. Otherwise you should use the lastErrorMessage and lastErrorMessage methods 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

    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 with pragma statements and the like. Second, note the lack of quotation marks in the SQL. The WHERE clause was not WHERE name='%@' (like you might have to do if you built a SQL statement using NSString method stringWithFormat ), but rather simply WHERE name=%@.

    Declaration

    Objective-C

    - (FMResultSet *_Nullable)executeQueryWithFormat:(nonnull NSString *)format,
                                                     ...;

    Parameters

    format

    The SQL to be performed, with printf-style escape sequences, followed by ptional parameters to bind to use in conjunction with the printf-style escape sequences in the SQL statement.

    Return Value

    A FMResultSet for the result set upon success; nil upon failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for diagnostic information regarding the failure.

  • Execute select statement

    Executing queries returns an FMResultSet object if successful, and nil upon failure. Like executing updates, there is a variant that accepts an NSError ** parameter. Otherwise you should use the lastErrorMessage and lastErrorMessage methods 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

    Declaration

    Objective-C

    - (FMResultSet *_Nullable)executeQuery:(nonnull NSString *)sql
                      withArgumentsInArray:(nonnull NSArray *)arguments;

    Swift

    func executeQuery(_ sql: String, withArgumentsIn arguments: [Any]) -> FMResultSet?

    Parameters

    sql

    The SELECT statement to be performed, with optional ? placeholders.

    arguments

    A NSArray of objects to be used when binding values to the ? placeholders in the SQL statement.

    Return Value

    A FMResultSet for the result set upon success; nil upon failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for diagnostic information regarding the failure.

  • Execute select statement

    Executing queries returns an FMResultSet object if successful, and nil upon failure. Like executing updates, there is a variant that accepts an NSError ** parameter. Otherwise you should use the lastErrorMessage and lastErrorMessage methods 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 a NSError pointer, 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

    Note

    When called from Swift, only use the first two parameters, sql and values. 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 -> FMResultSet

    Parameters

    sql

    The SELECT statement to be performed, with optional ? placeholders.

    values

    A NSArray of objects to be used when binding values to the ? placeholders in the SQL statement.

    error

    A NSError object to receive any error object (if any).

    Return Value

    A FMResultSet for the result set upon success; nil upon failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for diagnostic information regarding the failure.

  • Execute select statement

    Executing queries returns an FMResultSet object if successful, and nil upon failure. Like executing updates, there is a variant that accepts an NSError ** parameter. Otherwise you should use the lastErrorMessage and lastErrorMessage methods 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

    Declaration

    Objective-C

    - (FMResultSet *_Nullable)executeQuery:(nonnull NSString *)sql
                   withParameterDictionary:(NSDictionary *_Nullable)arguments;

    Swift

    func executeQuery(_ sql: String, withParameterDictionary arguments: [AnyHashable : Any]?) -> FMResultSet?

    Parameters

    sql

    The SELECT statement to be performed, with optional ? placeholders.

    arguments

    A NSDictionary of objects keyed by column names that will be used when binding values to the ? placeholders in the SQL statement.

    Return Value

    A FMResultSet for the result set upon success; nil upon failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for 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) -> FMResultSet

    Parameters

    sql

    SQL statement to prepare, generally with ? placeholders.

Transactions

  • 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 use beginExclusiveTransaction, instead, not only to make your intent explicit, but also to future-proof your code.

    Declaration

    Objective-C

    - (BOOL)beginTransaction;

    Swift

    func beginTransaction() -> Bool

    Return Value

    YES on success; NO on failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for 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() -> Bool

    Return Value

    YES on success; NO on failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for 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() -> Bool

    Return Value

    YES on success; NO on failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for 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() -> Bool

    Return Value

    YES on success; NO on failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for 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() -> Bool

    Return Value

    YES on success; NO on failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for 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() -> Bool

    Return Value

    YES on success; NO on failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for diagnostic information regarding the failure.

  • Identify whether currently in a transaction or not

    See

    beginTransaction

    See

    beginDeferredTransaction

    See

    commit

    See

    rollback

    Declaration

    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

Cached statements and result sets

  • 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

    YES if there are open result sets; NO if 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() -> Bool

    Return Value

    YES on success; NO on failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for diagnostic information regarding the failure.

Encryption methods

  • 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) -> Bool

    Parameters

    key

    The key to be used.

    Return Value

    YES if success, NO on 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) -> Bool

    Parameters

    key

    The key to be used.

    Return Value

    YES if success, NO on 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) -> Bool

    Parameters

    keyData

    The NSData to be used.

    Return Value

    YES if success, NO on 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) -> Bool

    Parameters

    keyData

    The NSData to be used.

    Return Value

    YES if success, NO on error.

General inquiry methods

  • 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 sqlite3 pointer.

Retrieving error codes

  • 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

    lastErrorCode

    See

    lastError

    Declaration

    Objective-C

    - (nonnull NSString *)lastErrorMessage;

    Swift

    func lastErrorMessage() -> String

    Return Value

    NSString of 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() -> Int32

    Return 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() -> Int32

    Return 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() -> Bool

    Return Value

    YES if there was an error, NO if no error.

  • Last error

    See

    lastErrorCode

    See

    lastErrorMessage

    Declaration

    Objective-C

    - (nonnull NSError *)lastError;

    Swift

    func lastError() -> Error

    Return Value

    NSError representing the last error.

  • Undocumented

    Declaration

    Objective-C

    @property (nonatomic) NSTimeInterval maxBusyRetryTimeInterval

    Swift

    var maxBusyRetryTimeInterval: TimeInterval { get set }

Save points

  • 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) throws

    Parameters

    name

    Name of save point.

    outErr

    A NSError object to receive any error object (if any).

    Return Value

    YES on success; NO on failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for 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) throws

    Parameters

    name

    Name of save point.

    outErr

    A NSError object to receive any error object (if any).

    Return Value

    YES on success; NO on failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for 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) throws

    Parameters

    name

    Name of save point.

    outErr

    A NSError object to receive any error object (if any).

    Return Value

    YES on success; NO on failure. If failed, you can call lastError , lastErrorCode , or lastErrorMessage for 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

    block

    Block of code to perform from within save point.

    Return Value

    The NSError corresponding to the error, if any. If no error, returns nil .

Checkpoint

  • Performs a WAL checkpoint

    Declaration

    Objective-C

    - (BOOL)checkpoint:(FMDBCheckpointMode)checkpointMode
                 error:(NSError *_Nullable *_Nullable)error;

    Swift

    func checkpoint(_ checkpointMode: FMDBCheckpointMode) throws

    Parameters

    checkpointMode

    The checkpoint mode for sqlite3_wal_checkpoint_v2

    error

    The NSError corresponding to the error, if any.

    Return Value

    YES on success, otherwise NO .

  • 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?) throws

    Parameters

    checkpointMode

    The checkpoint mode for sqlite3_wal_checkpoint_v2

    name

    The db name for sqlite3_wal_checkpoint_v2

    error

    The NSError corresponding to the error, if any.

    Return Value

    YES on success, otherwise NO .

  • 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>?) throws

    Parameters

    checkpointMode

    The checkpoint mode for sqlite3_wal_checkpoint_v2

    name

    The db name for sqlite3_wal_checkpoint_v2

    error

    The NSError corresponding to the error, if any.

    logFrameCount

    If 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.

    checkpointCount

    If 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

    YES on success, otherwise NO .

SQLite library status

  • Test to see if the library is threadsafe

    Declaration

    Objective-C

    + (BOOL)isSQLiteThreadSafe;

    Swift

    class func isSQLiteThreadSafe() -> Bool

    Return Value

    NO if and only if SQLite was compiled with mutexing code omitted due to the SQLITE_THREADSAFE compile-time option being set to 0.

  • Examine/set limits

    Declaration

    Objective-C

    - (int)limitFor:(int)type value:(int)newLimit;

    Swift

    func limit(for type: Int32, value newLimit: Int32) -> Int32

    Parameters

    type
    newLimit

    The 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() -> String

    Return 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., 0x0243 for version 2.4.3.

    Warning

    This routine will not work if any component of the version number exceeds 15. For example, if it is version 2.17.3 , this will max out at 0x2f3. For this reason, we would recommend using FMDBUserVersion and with NSNumericSearch option, e.g.
     NSComparisonResult result = [[FMDatabase FMDBUserVersion] compare:@"2.11.0" options:NSNumericSearch];
    

    @returns The version number in hexadecimal, e.g., 0x0243 for version 2.4.3. If any component exceeds what can be can be represented in four bits, we’ll max it out at 0xf .

    Declaration

    Objective-C

    + (SInt32)FMDBVersion;

    Swift

    class func fmdbVersion() -> Int32

Make SQL function

  • 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

    name

    Name of function.

    arguments

    Maximum number of parameters.

    block

    The 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) -> Int32

    Parameters

    value

    The 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) -> Int64

    Parameters

    value

    The 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) -> Double

    Parameters

    value

    The argument whose value to return.

    Return Value

    The double value.

  • Get NSData value 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

    value

    The 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

    value

    The 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

    context

    The 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

    value

    The integer value to be returned.

    context

    The 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

    value

    The long value to be returned.

    context

    The 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

    value

    The double value to be returned.

    context

    The context to which the value will be returned.

  • Return NSData object 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

    data

    The NSData object to be returned.

    context

    The 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

    value

    The string value to be returned.

    context

    The 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

    error

    The error string to be returned.

    context

    The 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

    errorCode

    The integer error code to be returned.

    context

    The 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

    context

    The 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

    context

    The context to which the error will be returned.

Date formatter

  • Generate an NSDateFormatter that 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 NSDateFormatter is 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) -> DateFormatter

    Parameters

    format

    A valid NSDateFormatter format string.

    Return Value

    A NSDateFormatter that 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() -> Bool

    Return Value

    YES if there is a date formatter; NO if 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, as NSDateFormatter is not thread-safe.

    Declaration

    Objective-C

    - (void)setDateFormat:(NSDateFormatter *_Nullable)format;

    Swift

    func setDateFormat(_ format: DateFormatter?)

    Parameters

    format

    Set 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

    s

    NSString to convert to NSDate .

    Return Value

    The NSDate object; or nil if 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

    date

    NSDate of date to convert to NSString .

    Return Value

    The NSString representation of the date; nil if no formatter is set.

Return results of SQL to variable

  • Return int value for query

    Note

    This is not available from Swift.

    Declaration

    Objective-C

    - (int)intForQuery:(nonnull NSString *)query, ...;

    Parameters

    query

    The SQL query to be performed, followed by a list of parameters that will be bound to the ? placeholders in the SQL query.

    Return Value

    int value.

  • Return long value for query

    Note

    This is not available from Swift.

    Declaration

    Objective-C

    - (long)longForQuery:(nonnull NSString *)query, ...;

    Parameters

    query

    The SQL query to be performed, followed by a list of parameters that will be bound to the ? placeholders in the SQL query.

    Return Value

    long value.

  • Return BOOL value for query

    Note

    This is not available from Swift.

    Declaration

    Objective-C

    - (BOOL)boolForQuery:(nonnull NSString *)query, ...;

    Parameters

    query

    The SQL query to be performed, followed by a list of parameters that will be bound to the ? placeholders in the SQL query.

    Return Value

    BOOL value.

  • Return double value for query

    Note

    This is not available from Swift.

    Declaration

    Objective-C

    - (double)doubleForQuery:(nonnull NSString *)query, ...;

    Parameters

    query

    The SQL query to be performed, followed by a list of parameters that will be bound to the ? placeholders in the SQL query.

    Return Value

    double value.

  • Return NSString value for query

    Note

    This is not available from Swift.

    Declaration

    Objective-C

    - (NSString *_Nullable)stringForQuery:(nonnull NSString *)query, ...;

    Parameters

    query

    The SQL query to be performed, followed by a list of parameters that will be bound to the ? placeholders in the SQL query.

    Return Value

    NSString value.

  • Return NSData value for query

    Note

    This is not available from Swift.

    Declaration

    Objective-C

    - (NSData *_Nullable)dataForQuery:(nonnull NSString *)query, ...;

    Parameters

    query

    The SQL query to be performed, followed by a list of parameters that will be bound to the ? placeholders in the SQL query.

    Return Value

    NSData value.

  • Return NSDate value for query

    Note

    This is not available from Swift.

    Declaration

    Objective-C

    - (NSDate *_Nullable)dateForQuery:(nonnull NSString *)query, ...;

    Parameters

    query

    The SQL query to be performed, followed by a list of parameters that will be bound to the ? placeholders in the SQL query.

    Return Value

    NSDate value.

Schema related operations

  • Does table exist in database?

    Declaration

    Objective-C

    - (BOOL)tableExists:(nonnull NSString *)tableName;

    Swift

    func tableExists(_ tableName: String) -> Bool

    Parameters

    tableName

    The name of the table being looked for.

    Return Value

    YES if table found; NO if 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 object
    • tbl_name - The name of the table to which the object references
    • rootpage - The page number of the root b-tree page for tables and indices
    • sql - The SQL that created the entity

    Declaration

    Objective-C

    - (FMResultSet *_Nullable)getSchema;

    Swift

    func getSchema() -> FMResultSet?

    Return Value

    FMResultSet of schema; nil on 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 number
    • name - The name of the column
    • type - The data type specified for the column
    • notnull - whether the field is defined as NOT NULL (i.e. values required)
    • dflt_value - The default value for the column
    • pk - Whether the field is part of the primary key of the table

    Declaration

    Objective-C

    - (FMResultSet *_Nullable)getTableSchema:(nonnull NSString *)tableName;

    Swift

    func getTableSchema(_ tableName: String) -> FMResultSet?

    Parameters

    tableName

    The name of the table for whom the schema will be returned.

    Return Value

    FMResultSet of schema; nil on 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) -> Bool

    Parameters

    columnName

    The name of the column.

    tableName

    The name of the table.

    Return Value

    YES if column exists in table in question; NO otherwise.

  • 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) -> Bool

    Parameters

    columnName

    The name of the column.

    tableName

    The name of the table.

    Return Value

    YES if column exists in table in question; NO otherwise.

  • Validate SQL statement

    This validates SQL statement by performing sqlite3_prepare_v2, but not returning the results, but instead immediately calling sqlite3_finalize.

    Declaration

    Objective-C

    - (BOOL)validateSQL:(nonnull NSString *)sql
                  error:(NSError *_Nullable *_Nullable)error;

    Swift

    func validateSQL(_ sql: String) throws

    Parameters

    sql

    The SQL statement being validated.

    error

    This is a pointer to a NSError object that will receive the autoreleased NSError object if there was any error. If this is nil , no NSError result will be returned.

    Return Value

    YES if validation succeeded without incident; NO otherwise.

Application identifier tasks

  • Retrieve application ID

    See

    setApplicationID:

    Declaration

    Objective-C

    @property (nonatomic) uint32_t applicationID;

    Swift

    var applicationID: UInt32 { get set }

    Return Value

    The uint32_t numeric 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 }

user version identifier tasks

  • Retrieve user version

    See

    setUserVersion:

    Declaration

    Objective-C

    @property (nonatomic) uint32_t userVersion;

    Swift

    var userVersion: UInt32 { get set }