如何使用sqlite prepare语句在iphone应用程序中的Sqlite数据库中插入数据

时间:2011-05-06 13:20:50

标签: iphone sqlite

-(void)insertDataImage_ID:(NSInteger)ID ImageName:(NSString*)Image Bookmark:(NSString*)Title
{
    [self checkAndCreateDB];

    sqlite3 *database;

    if (sqlite3_open([DBPath UTF8String], &database)==SQLITE_OK) {

        NSString *statement;
        sqlite3_stmt *compliedstatement;
        statement =[[NSString alloc]  initWithFormat:@"insert into tblBookMark values(%d, '%@' , '%@')", ID,Image, Title ];

        statement = [[NSString alloc] initWithFormat :@"select * from tblBookMark"];
        NSLog(@"T-1");

        const char *sqlstatement = [statement UTF8String];

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

            NSLog(@"T-2");
            if (SQLITE_DONE!=sqlite3_step(compliedstatement)) {

                NSLog(@"T-3");

                NSAssert1 (0,@"Error by inserting '%s'",sqlite3_errmsg(database));

                UIAlertView *AlertOK=[[UIAlertView alloc] initWithTitle:@"Error !" message:@"Error by inserting" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Yes",nil];
                [AlertOK show];
                [AlertOK release];
            }
            NSLog(@"T-4");
            sqlite3_finalize(compliedstatement);
        }
        NSLog(@"T-5");
    }
    sqlite3_close(database);
    NSLog(@"T-6");

}

此代码有什么问题。它没有显示任何错误,但它

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

代码流未输入此行,任何人都可以帮助我识别错误或建议我解决方案。

3 个答案:

答案 0 :(得分:1)

你根本没有做任何错误检查,难怪你不知道出了什么问题!

看一下sqlite 3 error codes。如果错误不是SQLITE_OK,那是什么?

if (sqlite3_prepare_v2(database, sqlstatement, -1, &compliedstatement, NULL) == SQLITE_OK) {
   ...
} else {
    NSLog(@"%i - %@", sqlite3_errcode(database), sqlite3_errmsg(database));
}

答案 1 :(得分:1)

代码

static sqlite3_stmt *insertStmt = nil;

if(insertStmt == nil) 
{
    insertSql = "INSERT INTO Loginchk (uname,password) VALUES(?,?)";
    if(sqlite3_prepare_v2(database, insertSql, -1, &insertStmt, NULL) != SQLITE_OK)
        NSAssert1(0, @"Error while creating insert statement. '%s'", sqlite3_errmsg(database));
}

sqlite3_bind_text(insertStmt, 1, [Gunameq UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(insertStmt, 2, [Gpassq UTF8String], -1, SQLITE_TRANSIENT);
if(SQLITE_DONE != sqlite3_step(insertStmt))
    NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
else
    NSLog("Inserted");
//Reset the add statement.
sqlite3_reset(insertStmt);
insertStmt = nil; 

答案 2 :(得分:1)

修复你的查询...“INSERT INTO tblBookMark(field1,field2)VALUES(”“,”“)”;