iOS sqllite 数据库

8 篇文章 0 订阅
1 篇文章 0 订阅


前言:现在的项目中 推送消息需要用到 数据库缓存从服务器推送过来的消息,demo代码如下:

//
//  MessageTool.m
//  testdataBase
//
//  Created by tinghou on 16/7/28.
//  Copyright © 2016年 tinghou. All rights reserved.
//

#import "MessageTool.h"
#import "FMDB.h"
@implementation MessageTool
static FMDatabase *_db;
+ (void)initialize
{
    //  NSCachesDirectory NSDocumentDirectory
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"messages.sqlite"];
    _db = [FMDatabase databaseWithPath:path];
    [_db open];
    
    DLog(@"path = %@",path);
  
//    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_message (id integer PRIMARY KEY, message blob NOT NULL);"];
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_message (id integer PRIMARY KEY, message blob NOT NULL);"];
}

+ (NSMutableArray *)messagesWithParams:(NSDictionary *)params
{
    NSString *sql = nil;
 
    sql = @"SELECT * FROM t_message;";
    FMResultSet *set = [_db executeQuery:sql];
    NSMutableArray *messages = [NSMutableArray array];
    while (set.next) {
        int ID = [set intForColumn:@"id"];
        DLog(@"ID = %d",ID);
        NSData *Data = [set objectForColumnName:@"message"];
//        NSString *isRead = [set objectForColumnName:@"isRead"];
//        NSString *isRead = [NSKeyedUnarchiver unarchiveObjectWithData:isReadData];
        NSDictionary *messageDic = [NSKeyedUnarchiver unarchiveObjectWithData:Data];
//        NSDictionary *dic = @{@"messageDic":messageDic,
//                                     @"isRead":isRead
//                                     };
        [messages addObject:messageDic];

    }
    return messages;
}
//删除
+(void)delete
{
    if ([_db open]) {
        NSString *deleteSql = [NSString stringWithFormat:
                               @"DELETE  FROM t_message;"];
        BOOL res = [_db executeUpdate:deleteSql];
        
        if (!res) {
            NSLog(@"error when delete db table");
        } else {
            NSLog(@"success to delete db table");
        }
//        [_db close];
    }
}
+ (void)resaveMessages:(NSMutableArray *)messages{
    for (NSDictionary *message in messages) {
        NSData *messageData = [NSKeyedArchiver archivedDataWithRootObject:message];
        [_db executeUpdateWithFormat:@"INSERT INTO t_message(message) VALUES ( %@);", messageData];
    }
}

+ (void)saveMessages:(NSMutableArray *)messages
{
    for (NSDictionary *message in messages) {
//        NSString *isRead = @"0";
        NSData *messageData = [NSKeyedArchiver archivedDataWithRootObject:message];
        [_db executeUpdateWithFormat:@"INSERT INTO t_message(message) VALUES ( %@);", messageData];
    }
}

@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值