开发者

Update table SQLIte in my iPhone App

I want to make it able in my app to insert data to sqlite database, and if the id for example is exist so to update this row.

i done the create with :

    if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {
            sqlite3_stmt *insertStmt = nil;

            if(insertStmt == nil) 
            {
                const char *insertSql = "INSERT INTO Category (id,name) VALUES(?,?)";
                if(sqlite3_prepare_v2(database, insertSql, -1, &a开发者_StackOverflow中文版mp;insertStmt, NULL) != SQLITE_OK)
                    NSAssert1(0, @"Error while creating insert statement. '%s'", sqlite3_errmsg(database));
            }

            sqlite3_bind_int(insertStmt, 1, 135);
            sqlite3_bind_text(insertStmt, 2, [@"fds" 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;
        }
        sqlite3_close(database);


Use the OR REPLACE qualifier:

INSERT OR REPLACE INTO Category ...

This relies on the existence of a UNIQUE constraint (usually the primary key) containing just the id column.


You can use following code for update:

-(void) Update:(NSString *)query {

sqlite3_stmt *statement=nil;

NSString *path = [self GetDatabasePath:DataBaseName] ;

if(sqlite3_open([path UTF8String],&databaseObj) == SQLITE_OK)
{
    if(sqlite3_prepare_v2(databaseObj, [query UTF8String], -1, &statement, NULL) == SQLITE_OK)
    {
        sqlite3_step(statement);
    }
    sqlite3_finalize(statement);
}
if(sqlite3_close(databaseObj) == SQLITE_OK){

}else{
    NSAssert1(0, @"Error: failed to close database on memwarning with message '%s'.", sqlite3_errmsg(databaseObj));
}

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜