LoginSignup
1
1

More than 5 years have passed since last update.

FMDBでSQL実行後に影響のあった行数を取得(INSERT OR REPLACEの挙動に注意)

Posted at

はじめに

SQLiteを使うため、FMDBを使用しています。
Insert・Updateを実行後、影響のあった行数を取得する必要がありました。

changesで取得できます

@property (nonatomic, retain) FMDatabase *db;

SQL実行直後に、FMDatabaseのインスタンスのchangeメソッド呼び出し。

        [self.db executeUpdate:sql withParameterDictionary:dic];
        result += [self.db changes];

FMDBでの実装は以下のようになっています。

FMDBより
- (int)changes {
    if (_isExecutingStatement) {
        [self warnInUse];
        return 0;
    }

    _isExecutingStatement = YES;

    int ret = sqlite3_changes(_db);

    _isExecutingStatement = NO;

    return ret;
}

おわりに

Updateで結果が0件の場合にInsertする、という場合で使用しました。

SQLiteのReplace句の挙動が予想と違ったためです。
予想「PK項目が存在しない場合はINSERT、存在する場合はUPDATEを行う」
実際「PK項目が存在しない場合はINSERT、存在する場合はDELETE後、INSERTを行う」

何かの参考になりましたら幸いです。

関連

FMDB

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1