sqlite3_step return code 21 during loadView
Experimenting with sqlite, I want to init a list view with data from the DB. My source looks like this:
-(void) initTheList {
sqlite3 *db;
int rows = 0;
const char* dbFilePathUTF8 = [searchTermDBLocation UTF8String];
int dbrc = sqlite3_open( dbFilePathUTF8, &db );
// count
if (dbrc) {
NSLog( @"Could not open the DB" );
} else {
NSString *queryStatementNS = @"select count(*) from article";
const char* queryStatement = [queryStatementNS UTF8String];
sqlite3_stmt *dbps;
dbrc = sqlite3_pre开发者_Go百科pare_v2(db, queryStatement, -1, &dbps, NULL);
if (sqlite3_step(dbps) == SQLITE_ROW) {
rows = sqlite3_column_int(dbps, 0);
} else {
NSLog(@"SQL step failed code: %d", sqlite3_step(dbps));
NSLog(@"Attempted Query: %@", queryStatementNS);
}
[queryStatementNS release];
}
if (rows > 1000) { ... } else { ... };
...
Actually I thought it would be good to envoke the code only one time once the view is loaded. So I added the initialization of the array and the method call to:
- (void)loadView {
[super loadView];
tableData = [[NSMutableArray alloc] initWithObjects:nil];
[self initTheList];
}
However, doing so, sqlite3_step returns x15 (SQLITE_MISUSE 21 /* Library used incorrectly */). If I place the code to invoke the method in the numberOfRowsInSection method, the call works fine.
Can somebody please give me a hint where I can learn more about the lifecycles and the relation to the sqlite database? It surprises me that I can open the DB but reading fails, while the same code placed in a method that is obviously called at a later point in time works fine.
I just ran into the error code 21 problem myself ("Library used incorrectly.") I couldn't find any helpful answers on the Web, and I was just about ready to conclude that there was some bug in the SQLite3 library in XCode. And then, at long last, I found my problem: a subtle typo in my SQL.
The error was happening during an INSERT OR REPLACE statement. But that particular statement itself had no typo, so I didn't find where I went wrong for the longest time. The database file was being created, so I ran a (Unix) strings command on it, and discovered that I had created a typo in one of the field names during the table's creation. The table created fine, but with the wrong field name. When I was doing the INSERT OR REPLACE, I was using the correct field name. Ah! The mismatch caused the error.
I don't know if this is your problem; but it is very easy to make a typo when creating SQL statements, and they aren't always easy to track down (as I just demonstrated to myself this afternoon). If I were you, I would double check every statement you have.
Hope this helps!
Today I discovered that error 21 is returned by sqlite3_step() if the prepared statement pointer happens to be NULL (zero).
精彩评论