Search code examples
objective-csqlitefmdb

FMDB Insert into with AutoIncrement


I'm trying to figure this out since a while but I can't seem to find a solution. I have a table that was created as:

 [db executeUpdate:@"CREATE TABLE 'MEDIA' (identifier INTEGER PRIMARY KEY AUTOINCREMENT, taskIdentifier INTEGER, type INTEGER, data BLOB)"]

How am I supposed to insert a record into this table? I tried this:

 [db executeUpdate:@"INSERT INTO 'MEDIA' VALUES($next_id,?,?,?)" withArgumentsInArray:arguments];

whereas arguments is an NSArray with 4 values, the first being a dummy value (since it should autoincrement itself) but to no avail. How is this supposed to work with FMDB?


Solution

  • You need to ask yourself if you really want to have the AUTOINCREMENT key word there. AUTOINCREMENT together with INTEGER PRIMARY KEY brings very specific behavior, which is described here. It is very likely that you don't need it, in which case just leave INTEGER PRIMARY KEY in the column definition. Now, columns defined as INTEGER PRIMARY KEY really become an alias of ROWID, so you have 2 options:

    • omit the value for this column in the INSERT statement. This will automatically insert the next available value there. From the docs: The usual algorithm is to give the newly created row a ROWID that is one larger than the largest ROWID in the table prior to the insert. So your INSERT would look like this:[db executeUpdate:@"INSERT INTO 'MEDIA' VALUES(?,?,?)" withArgumentsInArray:arguments]; but the arguments array would only contain 3 values for taskIdentifier, type, and data.

    • provide the value for identifier column like this: [db executeUpdate:@"INSERT INTO 'MEDIA' VALUES(?,?,?,?)" withArgumentsInArray:arguments]; with the arguments array containing the identifier as NSNumber on index 0.