Inherits from NSObject
Declared in FMDatabase.h
FMDatabase.m

Overview

A SQLite (http://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.

Tasks

Properties

Initialization

Opening and closing database

Perform updates

Retrieving results

Transactions

Cached statements and result sets

Encryption methods

General inquiry methods

Retrieving error codes

Save points

SQLite library status

Make SQL function

Date formatter

Properties

busyRetryTimeout

Busy retry timeout

@property (atomic, assign) int busyRetryTimeout

Declared In

FMDatabase.h

cachedStatements

Dictionary of cached statements

@property (atomic, retain) NSMutableDictionary *cachedStatements

Declared In

FMDatabase.h

checkedOut

Whether checked out or not

@property (atomic, assign) BOOL checkedOut

Declared In

FMDatabase.h

crashOnErrors

Crash on errors

@property (atomic, assign) BOOL crashOnErrors

Declared In

FMDatabase.h

logsErrors

Logs errors

@property (atomic, assign) BOOL logsErrors

Declared In

FMDatabase.h

traceExecution

Whether should trace execution

@property (atomic, assign) BOOL traceExecution

Declared In

FMDatabase.h

Class Methods

databaseWithPath:

Create a FMDatabase object.

+ (instancetype)databaseWithPath:(NSString *)inPath

Parameters

inPath

Path of database file

Return Value

FMDatabase object if successful; nil if failure.

Discussion

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 empty 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 create/open a database in your Mac OS X tmp folder:

FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];

Or, in iOS, you might open a database in the app’s Documents directory:

NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *dbPath   = [docsPath stringByAppendingPathComponent:@"test.db"];
FMDatabase *db     = [FMDatabase databaseWithPath:dbPath];

(For more information on temporary and in-memory databases, read the sqlite documentation on the subject: http://www.sqlite.org/inmemorydb.html)

Declared In

FMDatabase.h

isSQLiteThreadSafe

Test to see if the library is threadsafe

+ (BOOL)isSQLiteThreadSafe

Return Value

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

Declared In

FMDatabase.h

sqliteLibVersion

Run-time library version numbers

+ (NSString *)sqliteLibVersion

Declared In

FMDatabase.h

storeableDateFormat:

Generate an NSDateFormatter that won’t be broken by permutations of timezones or locales.

+ (NSDateFormatter *)storeableDateFormat:(NSString *)format

Parameters

format

A valid NSDateFormatter format string.

Return Value

A NSDateFormatter that can be used for converting dates to strings and vice versa.

Discussion

Use this method to generate values to set the dateFormat property.

Example:

myDB.dateFormat = [FMDatabase storeableDateFormat:@"yyyy-MM-dd HH:mm:ss"];

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.

Declared In

FMDatabase.h

Instance Methods

beginDeferredTransaction

Begin a deferred transaction

- (BOOL)beginDeferredTransaction

Return Value

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

Declared In

FMDatabase.h

beginTransaction

Begin a transaction

- (BOOL)beginTransaction

Return Value

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

Declared In

FMDatabase.h

changes

The number of rows changed by prior SQL statement.

- (int)changes

Discussion

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.

Declared In

FMDatabase.h

clearCachedStatements

Clear cached statements

- (void)clearCachedStatements

Declared In

FMDatabase.h

close

Closing a database connection

- (BOOL)close

Return Value

YES if success, NO on error.

Declared In

FMDatabase.h

closeOpenResultSets

Close all open result sets

- (void)closeOpenResultSets

Declared In

FMDatabase.h

commit

Commit a transaction

- (BOOL)commit

Return Value

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

Discussion

Commit a transaction that was initiated with either beginTransaction or with beginDeferredTransaction.

Declared In

FMDatabase.h

databasePath

The path of the database file

- (NSString *)databasePath

Return Value

path of database.

Declared In

FMDatabase.h

dateFromString:

Convert the supplied NSString to NSDate, using the current database formatter.

- (NSDate *)dateFromString:(NSString *)s

Parameters

s

NSString to convert to NSDate.

Return Value

nil if no formatter is set.

Declared In

FMDatabase.h

executeQuery:

Execute select statement

- (FMResultSet *)executeQuery:(NSString *)sql, ...

Parameters

sql

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

...

Optional parameters to bind to ? 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.

Discussion

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.

Declared In

FMDatabase.h

executeQuery:withArgumentsInArray:

Execute select statement

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

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.

Discussion

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.

Declared In

FMDatabase.h

executeQuery:withParameterDictionary:

Execute select statement

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

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.

Discussion

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.

Declared In

FMDatabase.h

executeQueryWithFormat:

Execute select statement

- (FMResultSet *)executeQueryWithFormat:(NSString *)format, ...

Parameters

format

The SQL to be performed, with printf-style escape sequences.

...

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

Discussion

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.

Warning: This should be used with great care. Generally, you should use executeQuery: (with ? placeholders) rather than this method.

Declared In

FMDatabase.h

executeUpdate:

Execute update statement

- (BOOL)executeUpdate:(NSString *)sql, ...

Parameters

sql

The SQL to be performed, with optional ? placeholders.

...

Optional parameters to bind to ? 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.

Declared In

FMDatabase.h

executeUpdate:withArgumentsInArray:

Execute update statement

- (BOOL)executeUpdate:(NSString *)sql withArgumentsInArray:(NSArray *)arguments

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.

Discussion

Any sort of SQL statement which is not a SELECT statement qualifies as an update. This includes CREATE, UPDATE, INSERT, ALTER, COMMIT, BEGIN, DETACH, DELETE, DROP, END, EXPLAIN, VACUUM, and REPLACE statements (plus many more). Basically, if your SQL statement does not begin with SELECT, it is an update statement.

Declared In

FMDatabase.h

executeUpdate:withParameterDictionary:

Execute update statement

- (BOOL)executeUpdate:(NSString *)sql withParameterDictionary:(NSDictionary *)arguments

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.

Discussion

Any sort of SQL statement which is not a SELECT statement qualifies as an update. This includes CREATE, UPDATE, INSERT, ALTER, COMMIT, BEGIN, DETACH, DELETE, DROP, END, EXPLAIN, VACUUM, and REPLACE statements (plus many more). Basically, if your SQL statement does not begin with SELECT, it is an update statement.

Declared In

FMDatabase.h

executeUpdateWithFormat:

Execute update statement

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

Parameters

format

The SQL to be performed, with printf-style escape sequences.

...

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.

Discussion

Any sort of SQL statement which is not a SELECT statement qualifies as an update. This includes CREATE, UPDATE, INSERT, ALTER, COMMIT, BEGIN, DETACH, DELETE, DROP, END, EXPLAIN, VACUUM, and REPLACE statements (plus many more). Basically, if your SQL statement does not begin with SELECT, it is an update statement.

Warning: This should be used with great care. Generally, you should use executeUpdate: (with ? placeholders) rather than this method.

Declared In

FMDatabase.h

goodConnection

Test to see if we have a good connection to the database.

- (BOOL)goodConnection

Return Value

YES if everything succeeds, NO on failure.

Discussion

This will confirm whether:

  • is database open
  • if open, it will try a simple SELECT statement and confirm that it succeeds.

Declared In

FMDatabase.h

hadError

Had error

- (BOOL)hadError

Return Value

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

Declared In

FMDatabase.h

hasDateFormatter

Test whether the database has a date formatter assigned.

- (BOOL)hasDateFormatter

Return Value

YES if there is a date formatter; NO if not.

Declared In

FMDatabase.h

hasOpenResultSets

Whether database has any open result sets

- (BOOL)hasOpenResultSets

Return Value

YES if there are open result sets; NO if not.

Declared In

FMDatabase.h

inSavePoint:

Start save point

- (NSError *)inSavePoint:(void ( ^ ) ( BOOL *rollback ))block

Parameters

block

Block of code to perform from within save point.

Return Value

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

Declared In

FMDatabase.h

inTransaction

Identify whether currently in a transaction or not

- (BOOL)inTransaction

Return Value

YES if currently within transaction; NO if not.

Declared In

FMDatabase.h

initWithPath:

Initialize a FMDatabase object.

- (instancetype)initWithPath:(NSString *)inPath

Parameters

inPath

Path of database file

Return Value

FMDatabase object if successful; nil if failure.

Discussion

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 empty 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 create/open a database in your Mac OS X tmp folder:

FMDatabase *db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];

Or, in iOS, you might open a database in the app’s Documents directory:

NSString *docsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *dbPath   = [docsPath stringByAppendingPathComponent:@"test.db"];
FMDatabase *db     = [FMDatabase databaseWithPath:dbPath];

(For more information on temporary and in-memory databases, read the sqlite documentation on the subject: http://www.sqlite.org/inmemorydb.html)

Declared In

FMDatabase.h

lastError

Last error

- (NSError *)lastError

Return Value

NSError representing the last error.

Declared In

FMDatabase.h

lastErrorCode

Last error code

- (int)lastErrorCode

Return Value

Integer value of the last error code.

Discussion

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.

Declared In

FMDatabase.h

lastErrorMessage

Last error message

- (NSString *)lastErrorMessage

Return Value

NSString of the last error message.

Discussion

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.

Declared In

FMDatabase.h

lastInsertRowId

Last insert rowid

- (sqlite_int64)lastInsertRowId

Discussion

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 INSERTs have ever occurred on that database connection, zero is returned.

Declared In

FMDatabase.h

makeFunctionNamed:maximumArguments:withBlock:

Adds SQL functions or aggregates or to redefine the behavior of existing SQL functions or aggregates.

- (void)makeFunctionNamed:(NSString *)name maximumArguments:(int)count withBlock:(void ( ^ ) ( sqlite3_context *context , int argc , sqlite3_value **argv ))block

Parameters

name

Name of function

count

Maximum number of parameters

block

The block of code for the function

Discussion

For example:

[queue inDatabase:^(FMDatabase *adb) {

    [adb executeUpdate:@"create table ftest (foo text)"];
    [adb executeUpdate:@"insert into ftest values ('hello')"];
    [adb executeUpdate:@"insert into ftest values ('hi')"];
    [adb executeUpdate:@"insert into ftest values ('not h!')"];
    [adb executeUpdate:@"insert into ftest values ('definitely not h!')"];

    [adb makeFunctionNamed:@"StringStartsWithH" maximumArguments:1 withBlock:^(sqlite3_context *context, int aargc, sqlite3_value **aargv) {
        if (sqlite3_value_type(aargv[0]) == SQLITE_TEXT) {
            @autoreleasepool {
                const char *c = (const char *)sqlite3_value_text(aargv[0]);
                NSString *s = [NSString stringWithUTF8String:c];
                sqlite3_result_int(context, [s hasPrefix:@"h"]);
            }
        }
        else {
            NSLog(@"Unknown formart for StringStartsWithH (%d) %s:%d", sqlite3_value_type(aargv[0]), __FUNCTION__, __LINE__);
            sqlite3_result_null(context);
        }
    }];

    int rowCount = 0;
    FMResultSet *ars = [adb executeQuery:@"select * from ftest where StringStartsWithH(foo)"];
    while ([ars next]) {
        rowCount++;
        NSLog(@"Does %@ start with 'h'?", [rs stringForColumnIndex:0]);
    }
    FMDBQuickCheck(rowCount == 2);
}];

Declared In

FMDatabase.h

open

Opening a new database connection

- (BOOL)open

Return Value

YES if successful, NO on error.

Discussion

The database is opened for reading and writing, and is created if it does not already exist.

Declared In

FMDatabase.h

openWithFlags:

Opening a new database connection with flags

- (BOOL)openWithFlags:(int)flags

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:

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.

Return Value

YES if successful, NO on error.

Declared In

FMDatabase.h

rekey:

Reset encryption key

- (BOOL)rekey:(NSString *)key

Parameters

key

The key to be used.

Return Value

YES if success, NO on error.

Discussion

Warning: You need to have purchased the sqlite encryption extensions for this method to work.

Declared In

FMDatabase.h

rekeyWithData:

Reset encryption key using keyData.

- (BOOL)rekeyWithData:(NSData *)keyData

Parameters

keyData

The NSData to be used.

Return Value

YES if success, NO on error.

Discussion

Warning: You need to have purchased the sqlite encryption extensions for this method to work.

Declared In

FMDatabase.h

releaseSavePointWithName:error:

Release save point

- (BOOL)releaseSavePointWithName:(NSString *)name error:(NSError **)outErr

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.

Declared In

FMDatabase.h

rollback

Rollback a transaction

- (BOOL)rollback

Return Value

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

Discussion

Rollback a transaction that was initiated with either beginTransaction or with beginDeferredTransaction.

Declared In

FMDatabase.h

rollbackToSavePointWithName:error:

Roll back to save point

- (BOOL)rollbackToSavePointWithName:(NSString *)name error:(NSError **)outErr

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.

Declared In

FMDatabase.h

setDateFormat:

Set to a date formatter to use string dates with sqlite instead of the default UNIX timestamps.

- (void)setDateFormat:(NSDateFormatter *)format

Parameters

format

Set to nil to use UNIX timestamps. Defaults to nil. Should be set using a formatter generated using FMDatabase::storeableDateFormat.

Discussion

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.

Declared In

FMDatabase.h

setKey:

Set encryption key.

- (BOOL)setKey:(NSString *)key

Parameters

key

The key to be used.

Return Value

YES if success, NO on error.

Discussion

Warning: You need to have purchased the sqlite encryption extensions for this method to work.

Declared In

FMDatabase.h

setKeyWithData:

Set encryption key using keyData.

- (BOOL)setKeyWithData:(NSData *)keyData

Parameters

keyData

The NSData to be used.

Return Value

YES if success, NO on error.

Discussion

Warning: You need to have purchased the sqlite encryption extensions for this method to work.

Declared In

FMDatabase.h

setShouldCacheStatements:

Set whether should cache statements or not

- (void)setShouldCacheStatements:(BOOL)value

Parameters

value

YES if should cache statements; NO if not.

Declared In

FMDatabase.h

shouldCacheStatements

Return whether should cache statements or not

- (BOOL)shouldCacheStatements

Return Value

YES if should cache statements; NO if not.

Declared In

FMDatabase.h

sqliteHandle

The underlying SQLite handle

- (sqlite3 *)sqliteHandle

Return Value

The sqlite3 pointer.

Declared In

FMDatabase.h

startSavePointWithName:error:

Start save point

- (BOOL)startSavePointWithName:(NSString *)name error:(NSError **)outErr

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.

Declared In

FMDatabase.h

stringFromDate:

Convert the supplied NSDate to NSString, using the current database formatter.

- (NSString *)stringFromDate:(NSDate *)date

Parameters

date

NSDate of date to convert to NSString.

Return Value

nil if no formatter is set.

Declared In

FMDatabase.h

update:withErrorAndBindings:

Execute update statement

- (BOOL)update:(NSString *)sql withErrorAndBindings:(NSError **)outErr, ...

Parameters

sql

The SQL to be performed, with optional ? placeholders.

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.

...

Optional parameters to bind to ? 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.

Declared In

FMDatabase.h