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;

  • 相关阅读:
    asp.net 连接 Access 的几种方法
    asp.net 连接 oracle10g 数据库
    Entity Framework实例
    LINQ链接数据库出错(There is already an open DataReader associated with this Command which must be closed first )
    Linq入门实例
    Nibatis实例(2)
    Log4net实例
    图片提交表单方法
    Nibatis实例(1)
    爱情是不离不弃吗?
  • 原文地址:https://www.cnblogs.com/hello-Huashan/p/4734753.html
Copyright © 2011-2022 走看看