zoukankan      html  css  js  c++  java
  • 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;

  • 相关阅读:
    iOS resign code with App Store profile and post to AppStore
    HTTPS科普扫盲帖 对称加密 非对称加密
    appid 评价
    使用Carthage安装第三方Swift库
    AngularJS:何时应该使用Directive、Controller、Service?
    xcode7 The operation couldn't be completed.
    cocoapods pod install 安装报错 is not used in any concrete target
    xcode7 NSAppTransportSecurity
    learning uboot how to set ddr parameter in qca4531 cpu
    learning uboot enable protect console
  • 原文地址:https://www.cnblogs.com/hello-Huashan/p/4734753.html
Copyright © 2011-2022 走看看