2011-05-10 8 views
2

EDIT : SOLVED! 첫 번째 코드 상자 아래의 대답SQLite 테이블이 존재하지 않습니다.

나는 (테이블 TblTest와 함께) sqlite 데이터베이스에 연결하려고 할 때. 내 응용 프로그램에서 디버그 모드에서 오류는 다음과 같습니다

*에서 어설 션 실패 - [QueryClass getTestData :] 때문에 캐치되지 않는 예외 'NSInternalInconsistencyException'응용 프로그램 종료, 이유는 * '캔트 항목을 [읽을 수있는 SQL을 구축 해당 테이블 없음 : TblTest] '

릴리스 모드 (시뮬레이터)에서는 오류가 발생하지 않지만 데이터베이스는 읽지 않습니다. 코드는 db에 연결할 수 있지만 TblTest를 읽을 수없는 것처럼 동작합니까?

이미 시뮬레이터를 재설정하고 깨끗한 빌드를 사용했습니다. 긴 코드에 대한 죄송합니다

는 :

@implementation QueryClass 
@synthesize databaseName; 
@synthesize databaseLite; 

-(id)initWithDatabase:(NSString *)databaseNameP{ 
    if(self = [super init]){ 
     [self createEditableCopyOfDatabaseIfNeeded]; 
     self.databaseName = databaseNameP; 
     self.databaseLite = [self getNewDBConnection]; 
    } 
    return self; 
} 

- (void)createEditableCopyOfDatabaseIfNeeded { 
    NSLog(@"Creating editable copy of database"); 
    // First, test for existence. 
    BOOL success; 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSError *error; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:self.databaseName]; 
    success = [fileManager fileExistsAtPath:writableDBPath]; 
    if (success) return; 
    // The writable database does not exist, so copy the default to the appropriate location. 
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:self.databaseName]; 
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; 
    if (!success) { 
     NSAssert1(0, @"Failed to create writable database file with message ‘%@’.", [error localizedDescription]); 
    } 
} 

- (sqlite3 *) getNewDBConnection{ 
    sqlite3 *newDBconnection; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *path = [documentsDirectory stringByAppendingPathComponent:self.databaseName]; 
    // Open the database. The database was prepared outside the application. 
    if (sqlite3_open([path UTF8String], &newDBconnection) == SQLITE_OK) { 

     NSLog(@"Database Successfully Opened "); 

    } else { 
     NSLog(@"Error in opening database "); 
    } 

    return newDBconnection; 
} 

-(NSMutableArray *)getTestData:(NSInteger) testId{ 
    (NSMutableArray *testArray = [[NSMutableArray alloc]init]; 

    int ret; 
    sqlite3_stmt *selStmt = nil; 
    const char *sql = "SELECT testId, name, FROM TblTest WHERE testId = ?"; 

    if (!selStmt) 
    { // build update statement 
     if (sqlite3_prepare_v2(self.databaseLite, sql, -1, &selStmt, NULL)!=SQLITE_OK) 
     { 
      selStmt = nil; 
     } 
    } 

    sqlite3_bind_int(selStmt, 1, testId); 

    if(!selStmt){ 
     NSAssert1(0, @"Cant build SQL to read item [%s]", sqlite3_errmsg(self.databaseLite)); 
    } 

    while ((ret=sqlite3_step(selStmt))==SQLITE_ROW) 
    { // get the fields from the record set and assign to item 

     Test *test = [[Test alloc]init]; 

     NSNumber *testId = [NSNumber numberWithInt: (int) sqlite3_column_int(selStmt, 0)]; 
     NSString *name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(selStmt, 1)]; 


     test.testId =testId; 
     test.name =name; 


     [testArray addObject:pill]; 
     [test release]; 
    } 
    sqlite3_reset(selStmt); 

    return [testArray autorelease]; 
} 



//in my function i do: 
qc = [[QueryClass alloc]initWithDatabase:@"databaseLite.sql"]; 
[qc getTestData:0]; 

나는 this 자습서를 사용하여 내 코드를 재 작성하고 그것이 마치 마법처럼 작동합니다. 당신이 당신의 자신의 문제를 해결하는 경우 :

감사

-(id)initWithDatabase:(NSString *)databaseNameP{ 
    if(self = [super init]){ 
     [self createEditableCopyOfDatabaseIfNeeded]; 
     [self initializeDatabase]; 
    } 
    return self; 
} 

// Creates a writable copy of the bundled default database in the application Documents directory. 
- (void)createEditableCopyOfDatabaseIfNeeded { 
    // First, test for existence. 
    BOOL success; 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSError *error; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"databaseLite4.sqlite"]; 
    success = [fileManager fileExistsAtPath:writableDBPath]; 
    if (success) return; 
    // The writable database does not exist, so copy the default to the appropriate location. 
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"databaseLite4.sqlite"]; 
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; 
    if (!success) { 
     NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]); 
    } 
} 

// Open the database connection and retrieve minimal information for all objects. 
- (void)initializeDatabase { 

    // The database is stored in the application bundle. 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    self.path = [documentsDirectory stringByAppendingPathComponent:@"databaseLite4.sqlite"]; 

} 
+0

'그런 테이블 : TblTest는'해당 테이블이 데이터베이스에 존재하지 않는 것을 의미한다. 오래된 데이터베이스가 있고 먼저 앱을 삭제해야하거나 테이블 이름의 철자가 잘못되었거나 그런 테이블을 만들지 않았습니다. 철자를 확인해 봤어? 아마 별거 아닐까? – vakio

답변

1

, 당신은 대답이 아니라 질문을 업데이트하는 등의 솔루션을 제공해야한다. 자신의 질문에 대답하고 대답으로 받아들이는 것이 가능합니다 (이 상황에서 권장). 당신은 당신 자신의 대답을 받아들이는데 어떤 평판도 얻지 못할 것이지만, 그 질문은 정확하게 해결 된 것으로 열거 될 것입니다.

다음은 귀하의 질문에서 추출한 답변입니다. 기꺼이 받아들이십시오.


나는 this 자습서를 사용하여 내 코드를 재 작성하고 그것이 마치 마법처럼 작동합니다. :)

여기 내 솔루션입니다 :

-(id)initWithDatabase:(NSString *)databaseNameP{ 
    if(self = [super init]){ 
     [self createEditableCopyOfDatabaseIfNeeded]; 
     [self initializeDatabase]; 
    } 
    return self; 
} 

// Creates a writable copy of the bundled default database in the application Documents directory. 
- (void)createEditableCopyOfDatabaseIfNeeded { 
    // First, test for existence. 
    BOOL success; 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSError *error; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"databaseLite4.sqlite"]; 
    success = [fileManager fileExistsAtPath:writableDBPath]; 
    if (success) return; 
    // The writable database does not exist, so copy the default to the appropriate location. 
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"databaseLite4.sqlite"]; 
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; 
    if (!success) { 
     NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]); 
    } 
} 

// Open the database connection and retrieve minimal information for all objects. 
- (void)initializeDatabase { 

    // The database is stored in the application bundle. 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    self.path = [documentsDirectory stringByAppendingPathComponent:@"databaseLite4.sqlite"]; 

} 
+0

당신에게 무료 크레딧;) – Oritm

관련 문제