Say I have a table MyTableName
with three columns: COLUMN_NAME_A
, COLUMN_NAME_B
, COLUMN_NAME_C
(only three for simplification, in practice I may have dozens of columns). With my current implementation, when I insert a new row, all columns will be overridden. How can I override only columns for which the new value is not null. One way, is to check the new value, and if it is NULL, read the value from the table and rewrite it.
Is there a more simple and/generic way to do so?
- (void)insertEntries:(<id<PTDBGeneralInfoTableEntry>>)entry inDatabase:(FMDatabase *)db {
[db beginTransaction];
[self createTableInDatabase:db];
NSString *insertSQL = [NSString stringWithFormat:@"INSERT OR REPLACE INTO MyTableName"
"(%@, %@, %@)"
" VALUES(?, ?, ?)",
COLUMN_NAME_A,
COLUMN_NAME_B,
COLUMN_NAME_C];
NSArray* values = @[entry.valueA ? entry.valueA : [NSNull null],
entry.valueB ? entry.valueB : [NSNull null],
entry.ValueC ? entry.ValueC : [NSNull null]];
BOOL res = [db executeUpdate:insertSQL withArgumentsInArray:values];
[db commit];
}
- (void)createTableInDatabase:(FMDatabase *)db {
NSString* createTableSQL =
[NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ ("
"%@ TEXT NOT NULL PRIMARY KEY,"
"%@ INTEGER,"
"%@ REAL"
")",
COLUMN_NAME_A,
COLUMN_NAME_B
COLUMN_NAME_C
];
[db executeUpdate:createTableSQL];
}