FMDB不会将NSData插入表中

时间:2014-10-23 14:32:50

标签: ios objective-c sqlite nsdata fmdb

我正在尝试将NSDictionary/NSArray中的一些数据添加到我的数据库中。我的项目使用sqlite / FMDB来完成它。但是我遇到了一些问题:我无法将NSData保存到我的数据库中 这是我的代码:

- (void)startSaveDB {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *path = [self databasePath];
    if ([fileManager fileExistsAtPath:path] == YES) {
        FMDatabase *database = [FMDatabase databaseWithPath:path];
        if (database) {
            [database open];
            [self createTableCacheApiWithDatabase:database];
            [self saveAPIwithJsonData:jsonData withParam:params withUrl:url withMethod:method withDatabase:database];
        }
        [database close];
    }
}

创建表格:

- (void)createTableCacheApiWithDatabase:(FMDatabase*)database {
    [database executeUpdate:@"create table if not exists APIENGINE_CACHE_TABLE (idx INTEGER NOT NULL DEFAULT 0 PRIMARY KEY AUTOINCREMENT, url Varchar NOT NULL, method Varchar NOT NULL, date_modified Varchar NULL, param BLOB NOT NULL, data BLOB NOT NULL);"];
}

将NSDictionary转换为NSData并保存:

- (void)saveAPIwithJsonData:(NSDictionary*)jsonData
                  withParam:(NSDictionary*)params
                    withUrl:(NSString*)url
                 withMethod:(NSString*)method
               withDatabase:(FMDatabase*)database {
    NSData *dataJson = [NSKeyedArchiver archivedDataWithRootObject:jsonData];
    NSData *dataParams = [NSKeyedArchiver archivedDataWithRootObject:params];
    if ([database open]) {
        [database executeQuery:@"insert into APIENGINE_CACHE_TABLE (param, data, url, method) values (?, ?, ?, ?);", [NSData dataWithData:dataParams], [NSData dataWithData:dataJson], url, method];
    }
}

路径:

- (NSString *) databasePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex: 0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:DATABASE_NAME];
    NSLog(@"path: %@", path);
    return path;
}

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:0)

这是一个老问题,但我偶然找到了解决问题的方法。答案是FMDabatase绑定NSData对象的值。 所以你不能使用格式化的字符串来插入NSData。而是使用(?,?,?)格式的查询。如果你真的想要一种格式化,你可以这样使用,

TABLE_USER, COL_CUSTOMER_ID, COL_IMAGE_PATH, COL_EXPIRY_DATE, COL_MOBILE_NUMBER是一些常量定义。

NSString * prepareStmt = [NSString stringWithFormat:
                    @"INSERT INTO %@ "
                    "(%@, %@, %@, %@) "
                    "VALUES  (?, ?, ?, ?) ",
                    TABLE_USER,
                    COL_CUSTOMER_ID, 
                    COL_IMAGE_PATH,
                    COL_EXPIRY_DATE,
                    COL_MOBILE_NUMBER];
    NSLog(@"Query: %@", prepareStmt);
    BOOL res = [self.dbConnection executeUpdate:prepareStmt, 
                userInfo.customerId, 
                userInfo.imagePath,
                userInfo.expiryDate, 
                userInfo.mobileNumber, nil];