zoukankan      html  css  js  c++  java
  • 将任意对象存进数据库

    #import "SXViewController.h"
    #import "SXShop.h"
    #import "FMDB.h"
    
    @interface SXViewController ()
    @property (nonatomic, strong) FMDatabase *db;
    @end
    
    @implementation SXViewController
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
        
        [self setup];
        
        [self readShops];
    }
    
    - (void)setup
    {
        // 初始化
        NSString *path = @"/Users/apple/Desktop/shops.data";
        self.db = [FMDatabase databaseWithPath:path];
        [self.db open];
        
        // 2.创表
        [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_shop (id integer PRIMARY KEY, shop blob NOT NULL);"];
    }
    
    - (void)readShops
    {
        FMResultSet *set = [self.db executeQuery:@"SELECT * FROM t_shop LIMIT 10,10;"];
        while (set.next) {
            NSData *data = [set objectForColumnName:@"shop"];
            SXShop *shop = [NSKeyedUnarchiver unarchiveObjectWithData:data];
            NSLog(@"%@", shop);
        }
        
    }
    
    - (void)addShops
    {
        
        for (int i = 0; i<100; i++) {
            SXShop *shop = [[SXShop alloc] init];
            shop.name = [NSString stringWithFormat:@"商品--%d", i];
            shop.price = arc4random() % 10000;
            
            NSData *data = [NSKeyedArchiver archivedDataWithRootObject:shop];
            [self.db executeUpdateWithFormat:@"INSERT INTO t_shop(shop) VALUES (%@);", data];
        }
    }
    
    @end
  • 相关阅读:
    关于flume配置加载
    ListMultimap 容器
    HotSpotOverview.pdf
    芝麻西瓜
    念念不忘必有回响
    phpstrom代码格式化
    小总结
    Redis支持的数据类型
    如何通过phpstorm查看某一行代码的变更记录
    mysql自动添加时间
  • 原文地址:https://www.cnblogs.com/songxing10000/p/4663152.html
Copyright © 2011-2022 走看看