批量NSArray写入SQLite

时间:2015-07-20 21:40:38

标签: ios objective-c sqlite

我试图使用SQLite事务将一个字典数组批量写入SQLite数据库以提高速度,因为数组可能变得非常大。

代码:

-(void)bulkCachetoSQLite:(NSArray *)dataToCache
{
    //Logging Comment
    NSLog(@"SQLiteClass - bulkCachetoSQLite");

    sqlite3_stmt *statement;
    const char *dbpath = [_filePath UTF8String];
    char * sErrMsg = 0;
    const char *tail = 0;

    if(sqlite3_open(dbpath, &_DB) == SQLITE_OK){

        char sSQL [BUFFER_SIZE] = "\0";
        sprintf(sSQL, "INSERT INTO livedata (device,datatype,timestamp,rawdata)");

        sqlite3_prepare_v2(_DB, sSQL, BUFFER_SIZE, &statement, &tail);
        sqlite3_exec(_DB, "BEGIN TRANSACTION", NULL, NULL, &sErrMsg);

        for (NSObject* data in dataToCache)
        {
            //NSLog(@"%@",data);

            sqlite3_bind_text(statement, 1, [[data valueForKey:@"device"] UTF8String], -1, SQLITE_TRANSIENT);
            sqlite3_bind_text(statement, 2, [[data valueForKey:@"type"] UTF8String], -1, SQLITE_TRANSIENT);
            sqlite3_bind_text(statement, 3, [[data valueForKey:@"timestamp"] UTF8String], -1, SQLITE_TRANSIENT);

            NSString *str = [[NSString alloc] initWithData:[data valueForKey:@"data"]  encoding:NSUTF8StringEncoding];
            sqlite3_bind_text(statement, 4, [str UTF8String], -1, SQLITE_TRANSIENT);

            sqlite3_step(statement);
            sqlite3_clear_bindings(statement);
            sqlite3_reset(statement);
        }

        sqlite3_exec(_DB, "END TRANSACTION", NULL, NULL, &sErrMsg);
        NSLog(@"SQLiteClass - bulkCachetoSQLite - EorrorA is %s", sErrMsg);
    }
    else{
        //db isn't open
    }
    NSLog(@"SQLiteClass - bulkCachetoSQLite - EorrorB is %s", sqlite3_errmsg(_DB));
    sqlite3_finalize(statement);
    sqlite3_close(_DB);
}

一切似乎没错ERRORS返回Null,但没有任何内容写入SQLite数据库。

db表结构是:

CREATE TABLE `livedata` (
    `ID`    INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
    `device`    TEXT,
    `datatype`  TEXT,
    `timestamp` TEXT,
    `rawdata`   TEXT
);

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

除了需要添加更多错误检查之外,您的INSERT不正确。你想要:

char *sSQL = "INSERT INTO livedata (device,datatype,timestamp,rawdata) VALUES (?,?,?,?)";