在此数据库中有一个名为“Menu”的表。我想在我的ViewController中打印此表,但此方法不起作用并立即关闭数据库。
在DatabaseMenu.h中:
@interface DatabaseMenu : NSObject {
sqlite3 *databaseMenu;
DataBaseMenu *rowMenu;
}
@property (nonatomic, assign) int ID;
@property (nonatomic, copy)NSString *descrizione;
@property (nonatomic, assign) BOOL haSubMenu;
@property (nonatomic, assign) int IDPadre;
@property (nonatomic, copy) NSString *tabelleFigli;
@property (nonatomic, assign) int ordine;
@property (nonatomic, copy) NSString *custView;
@property (nonatomic, assign) BOOL visMappa;
@property (nonatomic, copy) NSMutableArray *menuArray;
-(NSMutableArray*) loadDataFromMenu;
+(DatabaseMenu*) database;
@end
在DatabaseMenu.m中
static DatabaseMenu * database;
+(DatabaseMenu*) database{
if (database==nil) {
database =[[DatabaseMenu alloc]init];
}
return database;
}
-(NSMutableArray*) loadDataFromMenu{
NSString *query = @"SELECT * FROM Menu";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(databaseMenu, [query UTF8String], -1, &statement, nil)
== SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
//.......
}
sqlite3_finalize(statement);
} else {
sqlite3_close(databaseMenu);
}
return self.menuArray;
}
-(id) init{ //open database
self =[super init];
if(self){
NSString *sqliteDb = [[NSBundle mainBundle]pathForResource:@"China" ofType:@"sqlite"];
if(sqlite3_open([sqliteDb UTF8String], &databaseMenu)!=SQLITE_OK){
NSLog(@"Failed to open database");
}else {
NSLog(@"open the database");
[self loadDatiFromMenu];
}
return self;
}
}
调试器无法进入while循环。为什么呢?
答案 0 :(得分:0)
您在头文件中定义了一个实例变量database
,但在实现文件中也定义了一个静态变量database
(不是sqlite3对象)。
您确定在loadDataFromMenu
使用了正确的对象吗?
答案 1 :(得分:0)
您所做的不是从数据库中读取数据的正确方法。
在init之后,sqlite3变量必须首先打开数据库然后必须访问数据库,如下所示
if(!sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK)
{
NSLog(@"An error has occured");
}
const char *sql = "SELECT * FROM Menu";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(@"Problem with prepare statement.");
}
while(sqlite3_step(sqlStatement) == SQLITE_ROW)
{
//get all data from
}
此处dbPath
用于存储指向数据库的整个路径