2011-04-29 84 views
0

SQLite的INSERT语句不会插入新的数据

我使用这个代码

- (void) addN: (number *) theN 
{ 
    const char *sql = "insert into table (valueN) Values(?)"; 
    sqlite3_stmt *addStmt = nil; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); 
     NSString * docsDir = [paths objectAtIndex:0]; 
     NSString * thePath = [docsDir stringByAppendingPathComponent: @"theDB.sqlite"]; 
     sqlite3_open([thePath UTF8String], &database); 
     sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL); 
     sqlite3_bind_int(addStmt, 1, theN.theNumber); 
     sqlite3_step(addStmt); 
     sqlite3_finalize(addStmt); 
     sqlite3_close(database); 
    } 

和方法插入记录

SQLite的INSERT语句不会插入新的数据是

- (IBAction) saveN: (id) sender 
{ 
    numbers *theNumbers = [[numbers alloc] init]; 
    number *theNumber = [[number alloc] init]; 
    theNumber.theNumber = newN; 
    [theNumbers addN:theNumber]; 
    [theNumbers release]; 
    [theNumber release]; 
} 

代码已执行,但没有记录插入到数据库中。 有人可以请指出我的错误在哪里 - 因为那里显然是一个错误:)

+1

我没有回答过你的问题,但是当我看到所有已经进入刚插入一行到数据库中的努力 - 我可以看到为什么我使用核心数据! – Damien 2011-04-29 13:03:15

+0

您的第一个问题是您没有检查任何退货代码。你可能有错误,并且不知道它。 – 2013-07-11 15:37:39

回答

0

这段代码似乎工作:

- (void) addN: (number *) theN 
{ 
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSString *thePath = [[[NSBundle mainBundle] resourcePath] 
          stringByAppendingPathComponent:@"theDB.sqlite"]; 
    BOOL success = [fileManager fileExistsAtPath:thePath]; 
    if (!success) 
    { 
     NSLog(@"Failed to find database file '%@'.", thePath); 
    } 
    if (!(sqlite3_open([thePath UTF8String], &database) == SQLITE_OK)) 
    { 
     NSLog(@"An error opening database, normally handle error here."); 
    } 
    const char *sql = "insert into table (valueN) Values(?)"; 
    sqlite3_stmt *addStmt = nil; 
    if (sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK) 
    { 
     NSLog(@"Error, failed to prepare statement, normally handle error here."); 
    } 
    sqlite3_bind_int(addStmt, 1, theN.theNumber); 
    sqlite3_step(addStmt); 
    if(sqlite3_finalize(addStmt) != SQLITE_OK) 
    { 
     NSLog(@"Failed to finalize data statement, normally error handling here."); 
    } 
    if (sqlite3_close(database) != SQLITE_OK) 
    { 
     NSLog(@"Failed to close database, normally error handling here."); 
    } 
} 
0

你没有检查任何sqlite3调用的返回值。有一个很好的机会,其中一个失败。