简体   繁体   中英

How do I concatenate const char to const char?

I need to build up a const char string of other const char 's ?

const char *sql = "";
const char *sqlBuild = "";

for(int i=0; i < ac_count; ++i) {

  if (![sqlBuild isEqualToString:@""]) {
     sqlBuild = [sqlBuild stringByAppendingString:
           [NSString stringWithUTF8String:@" UNION "]];
  }
  sql = [[NSString stringWithFormat:
      @"select sum(price) from tmp%d  where due >= date() and due <= '%@'",  
            i, strDBDate] cStringUsingEncoding:NSUTF8StringEncoding];

  sqlBuild = [sqlBuild stringByAppendingString:
       [NSString stringWithUTF8String:sql]];
}

//execute sql

I've had several attempts but can't get it quite right, heres my last attempt. As you can see i'm trying to build up an sql statement.

Where am I going wrong ?

EDIT - I'm using sql lite which doesn't like NSString, see below.

- (NSString*)getCategoryDesc:(int)pintCid {

NSString *ret = @"";
const char *sql = "select category from categories where cid = ?";

sqlite3 *database;
int result = sqlite3_open([[General getDBPath] UTF8String], &database);
if(result != SQLITE_OK)
{
    DLog(@"Could not open db.");
}

sqlite3_stmt *statementTMP;

int error_code = sqlite3_prepare_v2(database, sql, -1, &statementTMP, NULL);

if(error_code == SQLITE_OK) {

    sqlite3_bind_int(statementTMP, 1, pintCid);

    if (sqlite3_step(statementTMP) == SQLITE_ROW) {
        ret = [[NSString alloc] initWithUTF8String:
            (char *)sqlite3_column_text(statementTMP, 1)];
    }
}
sqlite3_finalize(statementTMP);
sqlite3_close(database);


return [ret autorelease];
}

There's no benefit to the conversion to and then from a UTF8 string; it'd be much more efficient to do everything in NSString and convert it to a C-style string at the end. The @"d" syntax also evaluates to an object, not a C-style string.

So you should simplify and correct your code to:

NSMutableString *sqlStatement = [NSMutableString string];

for(int i=0; i < ac_count; ++i) {

  if ([sqlStatement length])  [sqlStatement appendString:@" UNION "];

  [sqlStatement appendFormat:
      @"select sum(price) from tmp%d  where due >= date() and due <= '%@'",  
            i, strDBDate];

}

// execute SQL string [sqlStatement UTF8String]

Declare sqlBuild to be NSMutableString and use that to build up your string:

NSMutableString *sqlBuild = [NSMutableString string];
for (...) {
    [sqlBuild appendString:...];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM