2012-01-27 2 views
1

SQLite3 DB에 3 개의 데이터를 추가하려고합니다. 튜토리얼의 도움으로 거의 다 왔어. 아래는 제 코드입니다.Xcode 내에서 SQLite3 DB에 데이터 추가

NSLogs에서 기대하는 바를 받고 있습니다. 문제없이 DB를 찾았습니다. DB에 문제없이 보낼 수있는 문을 컴파일했지만, 응용 프로그램이 sqlite3_prepare_v2(database, sqlstatement, -1, &compliedstatement, NULL)==SQLITE_OK에 도착하면 DB에 데이터가 추가 될 것으로 기대하지만, 그렇지 않습니다. 또한 기대하고 있습니다. 사용자에게 오류가 발생했음을 알리는 UIAlertView을 표시합니다. 내가하지 않은 것을 당신이 볼 수 있기를 바랍니다.

- (IBAction)addData:(id)sender { 
    NSString *n = [[NSString alloc] initWithString:[name text]]; 
    NSString *a = [[NSString alloc] initWithString:[age text]]; 
    NSString *c = [[NSString alloc] initWithString:[color text]]; 
    NSLog(@"%@ - %@ - %@",n,a,c); 
    [self insertDataName:n Age:a Color:c]; 
} 

NSLog은 예상대로 텍스트 속성을 반환합니다.

- (IBAction)hide:(id)sender { 
    [name resignFirstResponder]; 
    [age resignFirstResponder]; 
    [color resignFirstResponder]; 

} 



- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    DBName = @"mydatabase.sqlite"; 
    NSArray *documentsPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDir = [documentsPaths objectAtIndex:0]; 
    DBPath = [documentsDir stringByAppendingPathComponent:DBName]; 

} 


-(void)checkAndCreateDB { 
    BOOL Success; 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    Success = [fileManager fileExistsAtPath:DBPath]; 

    if(Success) { 
     NSLog(@"DB Found");  
     return; 
    } 

    NSLog(@"DB Not Found"); 
    NSString *databasePathFromApp = [[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:DBName]; 
    [fileManager copyItemAtPath:databasePathFromApp toPath:DBPath error:nil]; 

} 

NSLog 반환

-(void)insertData Name:(NSString*)n Age:(NSString*)a Color:(NSString*)c { 
    [self checkAndCreateDB]; 
    sqlite3 *database; 
    if (sqlite3_open([DBPath UTF8String],&database)==SQLITE_OK) { 
     NSString *statement; 
     sqlite3_stmt *compliedstatement; 
     statement = [[NSString alloc] initWithFormat:@"insert into table1 values ('%@', '%@', '%@')",n,a,c]; 
     const char *sqlstatement = [statement UTF8String]; 
     NSLog(@"%@",statement); 

     if (sqlite3_prepare_v2(database, sqlstatement, -1, &compliedstatement, NULL)==SQLITE_OK) { 

     if (SQLITE_DONE!=sqlite3_step(compliedstatement)) { 
      NSAssert1(0, @"Error by inserting '%s'", sqlite3_errmsg(database)); 
      UIAlertView *AlertOK = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"Error by inserting" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];  

      [AlertOK show]; 

     } 
     else { 
      UIAlertView *AlertOK = [[UIAlertView alloc] initWithTitle:@"Success!" message:@"Data successfully inserted" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];    
      [AlertOK show]; 
      } 
     } 
     sqlite3_finalize(compliedstatement); 

    } 
    sqlite3_close(database); 

} 

DB Found 내가 기대하는 것처럼 표시 insert into table1 values ('n', 'a', 'c') 위의 마지막 NSLog.

삽입시 문제가 발생하며 알아낼 수 없습니다.

FYI SQLiteManager를 사용하여 DB를 만들었습니다. SS 아래 :

SQLiteManager table1 SS

+0

정확히 무슨 일이 있었는지의 구체적 수 있습니까? 진술서가 준비되었지만 어떤 종류의 오류가 있습니까? 이 (SQLITE_DONE! = sqlite3_step (compliedstatement))이 실행 되었습니까? 그럼 어떻게 된거야? – Byte

+0

성공'UIAlertView'을 얻었지만 SQLiteManager에서 데이터베이스를 열고'select * from table1'을 열면 0 개의 항목이 있습니다. –

답변

1

좋아, 당신은 시뮬레이터 또는의 iDevice 작업을하고 있습니까? iDevice에서는 외부 지식을 가진 SQL 데이터베이스를 만들 수 없습니다. 샌드 박스 때문에 동적으로 생성해야합니다. "참고로 DB는 SQLiteManager를 사용하여 생성되었습니다." 그것을 확인하십시오.

그게 아니라면 문제는 ...에서

"실행"을 "... 준비"에서 코드를 변경

if (sqlite3_prepare_v2(database, sqlstatement, -1, &compliedstatement, NULL)==SQLITE_OK) { 

    if (SQLITE_DONE!=sqlite3_step(compliedstatement)) { 
     NSAssert1(0, @"Error by inserting '%s'", sqlite3_errmsg(database)); 
     UIAlertView *AlertOK = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"Error by inserting" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];  

     [AlertOK show]; 

    } 
    else { 
     UIAlertView *AlertOK = [[UIAlertView alloc] initWithTitle:@"Success!" message:@"Data successfully inserted" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];    
     [AlertOK show]; 
     } 
    } 
    sqlite3_finalize(compliedstatement); 

하려면를 ... 시도

sqlite3_exec(database, [sqlstatement UTF8String], NULL, NULL, &error); 

"필수 오류"때문에 로그온하지 마십시오.

당신이 UIAlert 팝업 원한다면

가 할이

if (error !=nil) 
    //show alert for error 
else 
    //show alert for success 
+0

위대한 답변,이 올바른 방향으로 나를 지적했다. 감사! –

관련 문제