将数据插入SQLite数据库表

时间:2012-07-05 09:34:43

标签: iphone ios

在我的应用程序中使用SQLite数据库来存储数据。 以下是用于插入数据的示例代码

在我的主要课程中调用这些方法如下

-(IBAction)insertButtonAction:(id)sender
{
BOOL isRollNum;
Database *db = [[Database alloc]init];
if ([rollNumberTxtFld.text length]>0)
{
    isRollNum = [db checkForRollNumber:rollNumberTxtFld.text];
    if (isRollNum == YES) 
    {
        UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Student with specified roll number already available" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [errorAlert show];
    }
    else
    {
        if ([nameTxtFld.text length]>0 && [rollNumberTxtFld.text length]>0  ) 
        {
            NSString *name = nameTxtFld.text;
            NSString *num = rollNumberTxtFld.text;
            int age = [ageTxtFld.text intValue];
            NSString *address1 = address1TxtFld.text;
            NSString *address2 = address2TxtFld.text;
            NSString *mobile = mobileTxtFld.text;
            NSString *class =classTxtFld.text;

            NSLog(@"%@ %@ %d %@ %@ %@ %@ ",name,num,age,address1,address2,mobile,class);

            NSString* insert_stmt = NULL;
            insert_stmt = [NSString stringWithFormat:@"insert into friends(name,rollnumber,age,address1,address2,mobile,class) values('%@', '%@', '%d', '%@', '%@', '%@', '%@')",name,num,age,address1,address2,mobile,class,nil ];  
            Database *db = [[Database alloc]init];
            BOOL inserted = [db insertIntoDB:insert_stmt];
            if (inserted == YES) 
            {
                insertReenterAlert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Inserted" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
                [insertReenterAlert show];
            }
            else
            {
                insertReenterAlert = [[UIAlertView alloc] initWithTitle:@"Failed" message:@"Not Inserted" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
                [insertReenterAlert show];
            }
        }
        else
        {
            insertReenterAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:@" Please enter required fields and try again." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [insertReenterAlert show];
        }
    }
}
else
{
    insertReenterAlert = [[UIAlertView alloc] initWithTitle:@"Error" message:@" Please enter required fields and try again." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
    [insertReenterAlert show];
}
}

此方法用于检查我们要插入的卷号是否已存在于DB表中。

-(BOOL)checkForRollNumber:(NSString *) num
{
rollNumberArray = [[NSMutableArray alloc] init];
NSFileManager *fileManager = [NSFileManager defaultManager];
dbPath = [[NSBundle mainBundle]pathForResource:@"FriendsList"ofType:@"sqlite"];
NSLog(@"dbPath %@",dbPath);    
BOOL success = [fileManager fileExistsAtPath:dbPath];
int rowCount = 0;
if (success)
{
    if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) 
    {
        const char* sqlStatement = "SELECT COUNT(rollnumber) FROM friends ";
        sqlite3_stmt* statement;
        if( sqlite3_prepare_v2(database, sqlStatement, -1, &statement, NULL) == SQLITE_OK ) 
        {
            if( sqlite3_step(statement) == SQLITE_ROW )
            rowCount  = sqlite3_column_int(statement, 0); 
        }
        else
        {
            NSLog( @"Failed from sqlite3_prepare_v2. Error is:  %s", sqlite3_errmsg(database) );
        }
        sqlite3_finalize(statement);
        sqlite3_close(database);
    }
}
NSLog(@"rowCount %d",rowCount);
if (success)
{
    if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
    {
        const char *selectSQL = "SELECT rollnumber FROM friends"; 
        sqlite3_stmt *statement;
        if (sqlite3_prepare_v2(database, selectSQL, -1, &statement, NULL) == SQLITE_OK)
        {
            while (sqlite3_step(statement) == SQLITE_ROW)
            {
                for ( int i=0; i<rowCount; i++ )
                {
                    NSLog(@"i    %d",i);
                    NSString *str = [NSString stringWithUTF8String:(char *) sqlite3_column_text(statement, 0)];
                    [rollNumberArray addObject:str];
                    NSLog(@"rollNumberArray: %@",[rollNumberArray objectAtIndex:i]);
                }
            }
            for ( int i=0; i<[rollNumberArray count]; i++ )
            {
                NSLog(@"[rollNumberArray objectAtIndex:%d] %@ == num %@",i,[rollNumberArray objectAtIndex:i],num);
                if ([[rollNumberArray objectAtIndex:i] intValue] == [num intValue])
                {
                     NSLog(@"FOUND");
                    return YES;
                }
                else
                {
                    NSLog(@"NOT FOUND");
                    return NO;
                }
            }
        }
        else
        {
            NSLog(@"Statement Not Prepared");
            return NO;
        }
        sqlite3_finalize(statement);
    }
    else
    {
        NSLog(@"Database Not Opened");
        return NO;
    }
    sqlite3_close(database);
}
else
{
    NSLog(@"File Not Opened");
    return NO;
}
}

这是将数据插入表

的方法
-(BOOL) insertIntoDB :(NSString *) insert_stmt 
{
NSFileManager *fileManager = [NSFileManager defaultManager];
dbPath = [[NSBundle mainBundle]pathForResource:@"FriendsList"ofType:@"sqlite"];
NSLog(@"dbPath %@",dbPath);    
BOOL success = [fileManager fileExistsAtPath:dbPath];
if (success)
{
    if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
    {
        const char *insertSQL = [insert_stmt UTF8String]; 
        sqlite3_stmt *statement;
        if (sqlite3_prepare_v2(database, insertSQL, -1, &statement, NULL) == SQLITE_OK) //**Always not entering into this if**
        {
            if (sqlite3_step(statement) == SQLITE_DONE)
            {
                NSLog(@"Succesfully added in DB");
                return YES;
            }
            else
            {
                 NSLog(@"Not added in DB");
                return NO;
            }
        }
        else
        {
            NSLog(@"Statement Not Prepared");
            return NO;
        }
        sqlite3_finalize(statement);
    }
    else
    {
        NSLog(@"Database Not Opened");
        return NO;
    }
    sqlite3_close(database);
}
else
{
    NSLog(@"File Not Opened");
    return NO;
}
}

不满足此条件 sqlite3_prepare_v2(数据库,selectSQL,-1,&amp;语句,NULL)== SQLITE_OK)  并且只有第一次添加值。 任何人都可以帮助或建议我。

提前致谢。

1 个答案:

答案 0 :(得分:0)

sqlite3_prepare_v2将返回您忽略的错误代码。为什么不将它赋给变量,以便在使用if语句测试它之前检查它?

int returnCode = sqlite3_prepare_v2(database, insertSQL, -1, &statement, NULL) 
if (returnCode == SQLITE_OK) // put a breakpoint here and look at return code.