在iPhone ios中从sqlite数据库获取行数

背景

我一整天都在努力解决一个问题,我读了所有可以在互联网上find的文章和文档,但是我无法解决这个问题。 我正在为iPhone编写一个应用程序,我需要使用一个sqlite数据库( sqlite3 )。

主要问题

我已经创build了我的数据库,一切都很好,直到我想得到我的表中的行数。 表名是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的东西是不正确的… …

感谢您的更新,我相信问题是你检查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; } 

从iPhone中的SQLite数据库获取行数(ios)

这是我的问题的解决scheme。 一个简单的解决scheme,只需要经验和Sqlite3数据库知识。

工作链接代码

 (int) GetArticlesCount { int articlesCount = 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 ) { if( sqlite3_step(statement) == SQLITE_ROW ) articlesCount = 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 articlesCount; }