【问题标题】:How can I update my sqlite database one row by row ? IOS如何逐行更新我的 sqlite 数据库? IOS
【发布时间】:2013-11-19 14:49:17
【问题描述】:

我想像 Android 一样逐行更新我的数据库 sqlite3,并使用索引来更新特定行。我该如何使用它?

-(void) updateBddWithData:(Data*) data{ 

    sqlite3 *databaseOK=self.database;

    if(sqlite3_open([self.databasePath UTF8String], &databaseOK) == SQLITE_OK) {

        NSString* updateIntoBdd = [NSString stringWithFormat:@"UPDATE ART_TABLE SET ida = '%@' ,title = '%@' ,chapo = '%@' ,link = '%@' ,linkimg = '%@' ,pubdate = '%@' ,creator = '%@' ,description = '%@'  ",data.ide,data.title,data.chapo,data.link,data.linkImg,data.pubDate,data.creator,data.description];

        sqlite3_stmt* statement = NULL;

        int returnValue = (sqlite3_prepare_v2(databaseOK, [updateIntoBdd UTF8String], -1, &statement, NULL));

        if(returnValue == SQLITE_OK){

            if(sqlite3_step(statement) == SQLITE_DONE){

             // What can I do ?

             }

        }
        sqlite3_finalize(statement);
        sqlite3_close(databaseOK);
    }
}

当我调用我的方法 Update(object) 时,我只想用我的参数对象更新一个索引行。

感谢提前

【问题讨论】:

  • 没有库就不行?
  • 是的,这是可能的,但你必须编写至少时间倍于没有库的代码,你应该首先选择行,然后 forech 行更新它,你应该处理类型/列...等等,使用库,您只需选择并编写另一个更新查询,所有其他(sqlite)内容将由库管理

标签: ios sqlite sql-update


【解决方案1】:

您在语句中缺少WHERE 子句。

通常,您在表中有一个ID(也许这是您的ida?),以便您可以使用:

UPDATE ART_TABLE SET ida = '%@', ... WHERE id ='%@';

还可以考虑使用更安全的sqlite3_bind_*

【讨论】:

  • 我的数据库中有一个 id,但它是自动递增的,我的 ida 它与数据库 id 不同。而且我只想用索引更新一行,直到我的数据库结束。
  • 因此,您必须使用UPDATE ... WHERE id=#,其中# 是您要更新的行中的id
【解决方案2】:

为避免重新发明轮子,我建议使用 FMDatabase 之类的包装器。

但是,如果你真的想不使用包装器:

-(void) updateBddWithData:(Data*) data { 

    sqlite3 *databaseOK=self.database;

    if(sqlite3_open([self.databasePath UTF8String], &databaseOK) == SQLITE_OK) {

        NSString* updateIntoBdd = [NSString stringWithFormat:@"INSERT OR REPLACE INTO ART_TABLE (ida, title, chapo, link, linkimg, pubdate, creator, description) VALUES ('%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@')", data.ide, data.title, data.chapo, data.link, data.linkImg, data.pubDate, data.creator, data.description];

        sqlite3_stmt* statement = NULL;

        const char *update_stmt = [insertSQL UTF8String];

        sqlite3_prepare_v2(databaseOK, insert_stmt,-1, &update_stmt, NULL);

        if (sqlite3_step(statement) == SQLITE_DONE) {
             //SUCCESS
        } 
        else {
            //ERROR
        }

        sqlite3_reset(statement);

        sqlite3_close(databaseOK);
    }
}

【讨论】:

  • 没有它就不可能?
  • @Pierre_S 这是可能的。检查我的编辑。我真的认为你应该试试 FMDatabase。它是一个非常易于使用且高性能的 sqlite 包装器
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多