从Document目录sqlite文件中读取数据

时间:2013-12-27 10:39:42

标签: ios objective-c sqlite

我正在使用这行代码。但我无法从表中读取数据。

- (void)viewDidLoad
{

    NSLog(@"value %@",[self filePath]);

    [self openDB];

    [self getAllRowsFromTableNamed:@"Authentication"];
}

- (void)didReceiveMemoryWarning
{


    [super didReceiveMemoryWarning];


}
-(NSString *) filePath
{

    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);


 NSString *documentDirectory=[paths objectAtIndex:0];


    return [documentDirectory stringByAppendingPathComponent:@"BM.sqlite"];

}

-(void)openDB
{

    if(sqlite3_open([[self filePath]UTF8String], & db) == SQLITE_OK)
    {

        sqlite3_close(db);

        NSAssert(0, @"Database failed to Open");
    }
}

-(void)getAllRowsFromTableNamed:(NSString *)tableName
{

    NSString *field1Str,*field2Str;

    NSString *qsql=[NSString stringWithFormat:@"SELECT * FROM %@",tableName];

    sqlite3_stmt *statement = nil;

    if(sqlite3_prepare_v2(db, [qsql UTF8String], -1, &statement, NULL) == SQLITE_OK)
    {
        while(sqlite3_step(statement) == SQLITE_ROW)
        {

            char *field1=(char *) sqlite3_column_text(statement, 0);
            char *field2=(char *) sqlite3_column_text(statement, 1);

            field1Str=[[NSString alloc]initWithUTF8String:field1];
            field2Str=[[NSString alloc] initWithUTF8String:field2];

            NSString *str=[NSString stringWithFormat:@"%@ - %@",field1Str,field2Str];
            NSLog(@"%@",str);
        }
    }

}

1 个答案:

答案 0 :(得分:0)

openDB中,您正在检查数据库是否已打开,如果打开,您正在关闭数据库!以下行导致问题:

if(sqlite3_open([[self filePath]UTF8String], & db) == SQLITE_OK)

将该方法更改为:

-(void)openDB
{
    if(sqlite3_open([[self filePath]UTF8String], & db) != SQLITE_OK)
    {
        NSAssert(0, @"Database failed to Open");
    }
}