ios数据存储--事务简单使用

FMDB事务:

在一个事务里面的操作,要么都成功,要么都不成功(不成功,数据库回滚)

- (void)事务的用法
{
    FMDatabase *database = [FMDatabase
                       databaseWithPath:[self databasePath]];
    if (![database open])
    {
        return;
    }
    NSString *sql = @"create table if not exists User (name text)";
    [database executeUpdate:sql];
    
    //第一步:添加事务
    [database beginTransaction];

    for (int i = 0; i < 50; i++)
    {
        BOOL isSuccess = [database executeUpdate:@"insert into User (name) values (?)", [NSString stringWithFormat:@"name%d",i+1]];
        if (!isSuccess)
        {
           //第二步:不成功,回滚数据库
            [database rollback];
            return;
        }
    }
    
    //第三步:提交,添加事务操作没有错误的需要提交事务,
    //当提交后才数据库进行操作
    [database commit];
}

|
|
微云网盘:事务demo

你可能感兴趣的:(ios数据存储--事务简单使用)