Hello all -
So I've scoured forums and Google, but I've been unable to figure out why this isn't working. Maybe someone here can help.
I have a sqlite call, and it opens the database, creates the array, etc. Everything is great. If I pass an "ORDER BY" in my sqlite const char string, it sorts as I expect.
However, I'd like to change the sort order programmatically, so naturally I want to use a variable so I can manipulate that outside the const char. So, I create an NSString, give it the column value I want, and test it.
No sorting change.
No errors, in console or anything, but no sorting change either. ???
Here's the relevant function that I'm trying to fix:
Code:
// Open the database connection and retrieve primary keys for all entries.
- (void)initializeDatabase {
NSMutableArray *uorArray = [[NSMutableArray alloc] init];
self.uors = uorArray;
[uorArray release];
// sort variable will go here, I'm testing with it coded as "Description". Description is a valid column name in my db.
NSString *orderBy = @"Description";
// The database is stored in the application bundle.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"uors.sqlite"];
// Open the database. The database was prepared outside the application.
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
// Get the primary key for all uors.
// If I change the end of this line to ORDER BY Description it works perfectly. ???
const char *sql = "SELECT pk FROM Vio_Code_order ORDER BY ?";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
// Bind the sort variable
sqlite3_bind_text(statement, 1, [orderBy UTF8String], -1, SQLITE_TRANSIENT);
// We "step" through the results - once for each row.
while (sqlite3_step(statement) == SQLITE_ROW) {
// The second parameter indicated the column index into the result set.
int primaryKey = sqlite3_column_int(statement, 0);
UORs *td = [[UORs alloc] initWithPrimaryKey:primaryKey database:database];
[uors addObject:td];
[td release];
}
}
// "Finalize" the statement - releases the resources associated with the statement.
sqlite3_finalize(statement);
} else {
// Even though the open failed, call close to properly clean up resources.
sqlite3_close(database);
NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
// Additional error handling, as appropriate...
}
}
Any thoughts? Thanks in advance!