无法在obj c中将数据插入sqlite数据库

时间:2011-05-20 07:21:06

标签: iphone objective-c sqlite

每个人都

我使用以下方法将数据插入数据库,但它将始终保存第一个输入的值 以下方法位于insertUpdateDelete类

- (void) InsertRecord {


    if(addStmt == nil) {

        NSString *nsql = [NSString stringWithFormat:@"insert into tbl_Users(FirstName,MiddleName) Values('%@','%@')",strFirstName,strMiddleName];
        const char *sql = [nsql UTF8String];



        if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK)
        {
            NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));

        }
    }



    if(SQLITE_DONE != sqlite3_step(addStmt))
        NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
    else
        //SQLite provides a method to get the last primary key inserted by using sqlite3_last_insert_rowid
        intID = sqlite3_last_insert_rowid(database);

    //Reset the add statement.
    sqlite3_reset(addStmt);
}

通过以下代码我调用这个方法,tfText [0]& tfText [1]是文本字段变量,问题是,在文本字段中输入一些数据后,每次点击保存,它只会将第一个输入的值保存到数据库中

 - (void) save_Clicked
    {


        iICS_testAppDelegate *appDelegate = (iICS_testAppDelegate *)[[UIApplication sharedApplication] delegate];

        //Create a Items Object.
        insertUpdateDelete *objInsertUpdateDelete = [[insertUpdateDelete alloc] init];

        objInsertUpdateDelete.strFirstName = tfText[0].text;
        objInsertUpdateDelete.strMiddleName = tfText[1].text;

        [appDelegate InsertRecord:objInsertUpdateDelete];

    }

任何人都可以提前帮助我,,,, thanx

1 个答案:

答案 0 :(得分:2)

const char *addRecord = "insert into Test(taskname, desc) values(?, ?)";
sqlite3_stmt *statement;

if(sqlite3_prepare_v2(database, addRecord, -1, &statement, NULL) != SQLITE_OK)
{
    NSLog(@"Error while Inserting Record :- '%s'", sqlite3_errmsg(database));
    sqlite3_finalize(statement);
    return -1;
}

sqlite3_bind_text(statement, 1, [Ttitle UTF8String], -1, SQLITE_TRANSIENT);

sqlite3_bind_text(statement, 3, [Tdesc UTF8String], -1, SQLITE_TRANSIENT);

if(SQLITE_DONE != sqlite3_step(statement))
{
    NSLog(@"Error1 while Inserting Record :- '%s'", sqlite3_errmsg(database));
    sqlite3_finalize(statement);
    return -1;
}
else 
{
    NSLog(@"Record Inserted Successfully.");
    sqlite3_finalize(statement);
    return sqlite3_last_insert_rowid(database);
}