Background
All day long I've been trying to solve a problem, I read all the articles and documentation that I could find on the Internet, but I can't solve this. I'm writing an application for iPhone and I need to work with a sqlite database (sqlit开发者_开发知识库e3).
Main Problem
I have created my database and all is going good until I wanted to get a count of the rows in my table. The Table name is ARTICLES
, so I wrote
SELECT COUNT(*) FROM ARTICLES
My program does nothing and writes in the log: Unknown Error.
const char *query = "SELECT COUNT (*) FROM ARTICLES";
sqlite3_stmt *compiledQuery;
sqlite3_prepare_v2(database, query, -1, &compiledQuery, NULL);
Program gives message "Unknown Error" in the above code, and I can't get the count of rows. Who can help me to solve this problem... or may be something with sqlite is not correct?
Code
- (int) GetArticlesCount
{
if (sqlite3_open([self.dataBasePath UTF8String], &articlesDB) == SQLITE_OK)
{
const char* sqlStatement = "SELECT COUNT(*) FROM ARTICLES";
sqlite3_stmt *statement;
if( sqlite3_prepare_v2(articlesDB, sqlStatement, -1, &statement, NULL) == SQLITE_OK )
{
if( sqlite3_step(statement) == SQLITE_DONE )
{
}
else
{
NSLog( @"Failed from sqlite3_step. Error is: %s", sqlite3_errmsg(articlesDB) );
}
}
else
{
NSLog( @"Failed from sqlite3_prepare_v2. Error is: %s", sqlite3_errmsg(articlesDB) );
}
// Finalize and close database.
sqlite3_finalize(statement);
sqlite3_close(articlesDB);
}
return 0;
}
In this line the unknown error appears:
NSLog( @"Failed from sqlite3_step. Error is: %s", sqlite3_errmsg(articlesDB) );
What must I add to the code or what must I do to get the count of rows? Please help...
Working Code (Not effective)
const char* sqlStatement = "SELECT * FROM ARTICLES";
sqlite3_stmt *statement;
if( sqlite3_prepare_v2(articlesDB, sqlStatement, -1, &statement, NULL) == SQLITE_OK )
{
int count = 0;
while( sqlite3_step(statement) == SQLITE_ROW )
count++;
}
I get the right count of rows! But I don't think it is an effective method... I think that something with sqlite is not going right...
Thank you for the update, I believe the problem is your check against SQLITE_DONE
instead of SQLITE_ROW
, so I have updated your method below:
- (int)getArticlesCount {
int count = 0;
if (sqlite3_open([self.dataBasePath UTF8String], &articlesDB) ==
SQLITE_OK) {
const char* sqlStatement = "SELECT COUNT(*) FROM ARTICLES";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(articlesDB, sqlStatement, -1, &statement, NULL) ==
SQLITE_OK) {
// Loop through all the returned rows (should be just one)
while(sqlite3_step(statement) == SQLITE_ROW) {
count = sqlite3_column_int(statement, 0);
}
} else {
NSLog(@"Failed from sqlite3_prepare_v2. Error is: %s",
sqlite3_errmsg(articlesDB));
}
// Finalize and close database.
sqlite3_finalize(statement);
sqlite3_close(articlesDB);
}
return count;
}
精彩评论