Question

I'm inserting value to database table. I have statement to get data and insert. If i don't have any value i need to insert blank instead of NULL

[parentDict setObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 5)== NULL?"":(char *)sqlite3_column_text(compiledStatement, 5)] forKey:@"AM_Answer"];
Was it helpful?

Solution

Generally, you'd insert [NSNull null] in your dictionary, to indicate a null value:

const char *column5 = sqlite3_column_text(compiledStatement, 5);

if (column5 == NULL)
    [parentDict setObject:[NSNull null] forKey:@"AM_Answer"];
else
    [parentDict setObject:[NSString stringWithUTF8String:(char *) column5] forKey:@"AM_Answer"];

You could also use a zero-length string (e.g. @""), but generally it's preferable to distinguish between a null value and a zero-length string.


In terms of insert null values into a database, you can either use the SQL NULL value:

int rc;

if ((rc = sqlite3_exec(db, "insert into test (column_a, column_b) values ('valueA', null)", NULL, NULL, NULL)) != SQLITE_OK)
    NSLog(@"insert failed %d: %s", rc, sqlite3_errmsg(db));

or, if you're doing dynamic binding of values, you can use the sqlite3_bind_null() function:

sqlite3_stmt *statement;

if ((rc = sqlite3_prepare_v2(db, "insert into test (column_a, column_b) values (?, ?)", -1, &statement, NULL)) != SQLITE_OK)
    NSLog(@"prepare failed %d: %s", rc, sqlite3_errmsg(db));

NSString *valueA = @"valueA";
if ((rc = sqlite3_bind_text(statement, 1, [valueA UTF8String], -1, SQLITE_TRANSIENT)) != SQLITE_OK)
    NSLog(@"bind a failed %d: %s", rc, sqlite3_errmsg(db));

if ((rc = sqlite3_bind_null(statement, 2)) != SQLITE_OK)
    NSLog(@"bind b failed %d: %s", rc, sqlite3_errmsg(db));

if ((rc = sqlite3_step(statement)) != SQLITE_DONE)
    NSLog(@"step failed %d: %s", rc, sqlite3_errmsg(db));

sqlite3_finalize(statement);

This latter example is greatly simplified if you use FMDB:

BOOL success = [db executeUpdate:@"insert into test (column_a, column_b) values (?, ?)", @"valueA", [NSNull null]];
if (!success)
    NSLog(@"Insert failed: %@", [db lastErrorMessage]);

OTHER TIPS

You are simply feeling parentDict. Once you put all the values inside it, check for the keys for which you want not NULL value.

if([parentDict objectForKey:@"AM_Answer"] == NULL)
     [parentDict setObject:@"" forKey:@"AM_Answer"];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top