我整天都试图解决问题,我阅读了我可以在互联网上找到的所有文章和文档,但我无法解决这个问题。我正在为iPhone编写应用程序,我需要使用 sqlite 数据库( sqlite3 )。
我已经创建了我的数据库,所有这些都很顺利,直到我想要计算表格中的行数。表名是ARTICLES
,所以我写了
SELECT COUNT(*) FROM ARTICLES
我的程序什么都不做,并在日志中写道: 未知错误。
const char *query = "SELECT COUNT (*) FROM ARTICLES";
sqlite3_stmt *compiledQuery;
sqlite3_prepare_v2(database, query, -1, &compiledQuery, NULL);
程序在上面的代码中给出了消息“ 未知错误 ”,我无法获得行数。 谁能帮我解决这个问题...或者可能是sqlite的东西不正确?
- (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;
}
在此行中会显示未知错误:
NSLog( @"Failed from sqlite3_step. Error is: %s", sqlite3_errmsg(articlesDB) );
我必须在代码中添加什么,或者我必须做些什么来获取行数?请帮忙......
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++;
}
我得到正确的行数!但我不认为这是一种有效的方法...我认为sqlite的东西不对......
答案 0 :(得分:43)
感谢您的更新,我相信问题是您对SQLITE_DONE
而不是SQLITE_ROW
的检查,所以我更新了您的方法:
- (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;
}