2014-02-13 143 views
0

我想从一个sqlite表中复制一些blob数据到另一个在C++中。但是,一旦数据被复制到新表中,它似乎正在被损坏。所述数据包含一些jpeg图像。我使用从TABLE1复制到TABLE2的代码如下所示:C++从一个数据库复制sqlite blob到另一个

// Read the blob from the database 
    int64_t rowID = 0; 
    sscanf(id.c_str(), "%llu", &rowID); 

    sqlite3_blob* blobHandle = NULL; 
    if(sqlite3_blob_open(m_dbHandle_temp, "main", m_currentTileTable.c_str(), "tile_data", rowID, 0, &blobHandle) != SQLITE_OK) 
    { 
     sqlite3_blob_close(blobHandle); // An SQLite blob will be initialised regardless of the success of 'sqlite3_blob_open' 
     return false; 
    } 


    tiles_insert_statement.append(")"); 

    // Copy blob to database 
    sqlite3_stmt *stmt = 0; 
    const char* tail; 
    sqlite3_prepare_v2(m_dbHandle, tiles_insert_statement.c_str(), strlen(tiles_insert_statement.c_str())+1, &stmt, &tail); 
    int bindSuccess = sqlite3_bind_blob(stmt, 1, blobHandle, sqlite3_blob_bytes(blobHandle), SQLITE_TRANSIENT); 
    if(sqlite3_step(stmt) != SQLITE_DONE) 
     printf("Error message: %s\n", sqlite3_errmsg(m_dbHandle)); 
    sqlite3_finalize(stmt); 

    // close handles 
    sqlite3_blob_close(blobHandle); 

有什么我做错了在上面的代码,我说,这是越来越损坏的原因是因为,我读了在Android设备上的斑点将显示在图像查看器中。表1中的斑点可以被读取并正常显示,但表2中的斑点不显示任何内容。任何帮助都非常容易理解。

SOLUTION:

// Read the blob from the database 
    int64_t rowID = 0; 
    sscanf(id.c_str(), "%llu", &rowID); 

    sqlite3_blob* blobHandle = NULL; 
    if(sqlite3_blob_open(m_dbHandle_temp, "main", m_currentTileTable.c_str(), "tile_data", rowID, 0, &blobHandle) != SQLITE_OK) 
    { 
     sqlite3_blob_close(blobHandle); // An SQLite blob will be initialised regardless of the success of 'sqlite3_blob_open' 
     return false; 
    } 

    unsigned int length = sqlite3_blob_bytes(blobHandle); 

    // TODO - instances of this class OWN the buffer. 
    // Delete the buffer in the destructor ;) 
    unsigned char* buffer = new unsigned char[ length ]; 
    if(sqlite3_blob_read(blobHandle, buffer, length, 0) != SQLITE_OK) 
    { 
     return false; 
    } 

    tiles_insert_statement.append(")"); 

    sqlite3_stmt *stmt = 0; 
    const char* tail; 
    sqlite3_prepare_v2(m_dbHandle, tiles_insert_statement.c_str(), strlen(tiles_insert_statement.c_str())+1, &stmt, &tail); 
    int bindSuccess = sqlite3_bind_blob(stmt, 1, buffer, length, SQLITE_TRANSIENT); 
    if(sqlite3_step(stmt) != SQLITE_DONE) 
     printf("Error message: %s\n", sqlite3_errmsg(m_dbHandle)); 
    sqlite3_finalize(stmt); 

    // close handles 
    sqlite3_blob_close(blobHandle); 
+0

也许你最好把一个数据库附加到另一个数据库并在sql查询中执行blob副本? – fnc12

回答

2

sqlite3_bind_blob需要一个指向实际blob数据;不可能为此使用blob句柄。

要将blob数据作为内存块执行,请执行如SELECT tile_data FROM MyTable WHERE ...的查询并使用sqlite3_column_blob读取该值。

+0

我编辑了我的问题以显示我最终做了什么。在回到这篇文章之前,我想到了它。正如你所建议的,这个问题是由于我已经将blob句柄传递给sqlite3_bind_blob – kushaldsouza

相关问题