• 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;

  • 相关阅读:
    Hash(学习笔记)
    [POI2012]OKR-A Horrible Poe(hash+线性筛素数)
    质数(学习笔记)
    [AHOI2014/JSOI2014]宅男计划(贪心+三分)
    [HEOI2015]定价(贪心+数学)
    Trie字典树(学习笔记)
    CF258D. Little Elephant and Broken Sorting(DP+概率期望)
    矩阵(01背包+滚动数组)
    [2015北大自招夏令营]产品排序(区间DP)
    HTML
  • 原文地址:https://www.cnblogs.com/hello-Huashan/p/4734753.html
Copyright © 2020-2023  润新知