iOS-防止向SQLite数据库中插入重复数据记录:

原则:先检测该数据库的指定表中,是否已经存在我们要插入的这条数据记录,若已经存在,则不插入这条数据记录(即忽略此次插入操作),若尚不存在,才插入这条数据记录(即才执行此次插入操作)

我们这里使用的是FMDB框架

方法一:

FMDatabase *collectionBookDB = [FavoriteBooksDataBase favoriteBooksDataBase];

    NSString *sqlObjectiveString = [NSString stringWithFormat:@"INSERT INTO t_favoriteBooks (bookName, author, publisher, publishmentDate, briefIntroduction, bookImageURL, bookIdentifier) SELECT '%@','%@','%@','%@','%@','%@', %d WHERE NOT EXISTS (SELECT * FROM t_favoriteBooks WHERE bookIdentifier=%d)", book.bookName, book.author, book.publisher, book.publishmentDate, book.briefIntroduction, book.bookImageURL, book.bookIdentifier, book.bookIdentifier];

 BOOL collectionBookResult = [collectionBookDB executeUpdate:sqlObjectiveString];

方法二:

FMDatabase *saveDB = [FavoriteBooksDataBase favoriteBooksDataBase];

    // 先查询数据库的表中有没有这个标识的书

    FMResultSet *resultSet = [saveDB executeQuery:[NSString stringWithFormat:@"SELECT * FROM t_favoriteBooks WHERE bookIdentifier = %d;", book.bookIdentifier]];

    if ([resultSet next]) { // 表中已经有这个标识的书了

        return NO; // 那就直接返回,即不执行插入操作

     }

    // 若表中还没有这个标识的书,就执行这次插入操作

    BOOL result = [saveDB executeUpdateWithFormat:@"INSERT INTO t_favoriteBooks (bookName, author, publisher, publishmentDate, briefIntroduction, bookImageURL, bookIdentifier) VALUES (%@,%@,%@,%@,%@,%@,%d) ", book.bookName, book.author, book.publisher, book.publishmentDate, book.briefIntroduction, book.bookImageURL, book.bookIdentifier]

if (!result) {

        NSLog(@"该条数据记录尚不存在于该表中,但插入操作失败");

        return NO;

    }

    return result;

 

posted on 2015-08-16 20:57  FCBayern  阅读(1208)  评论(0编辑  收藏  举报

导航