How to get BLOB data using oracle ODBC

2019-09-03 12:52发布

I'm trying to get image that are stored in BLOB and then save it as jpg.

Here i retrieve the binary data and save it in str;

  string str;
  SQLCHAR buf[500] = {0};
  while ((SQL_SUCCEEDED(SQLGetData(StmtHandle, colnum, SQL_C_BINARY, buf, sizeof(buf), NULL))))
  {
     string data(reinterpret_cast< const char* >(buf), reinterpret_cast< const char* >(buf) +    sizeof(buf));
     str = str + data;
  }

Then i write it in the file

ofstream file;  
file.open("C:\\Users\\tom\\Desktop\\img.jpeg");
file << str;
file.close();

and i get the incorrect image.

What's wrong with this method of data extraction (i used this) ?

标签: c++ oracle odbc
1条回答
劫难
2楼-- · 2019-09-03 13:16

I'm not familiar with ODBC programming, but at first sight, one issue I can see is that you assume your data length is multiple of your buffer size. But the last read is not guaranteed to return exactly 500 bytes of data.

You should write something like that. Maybe:

  string str;
  SQLCHAR buf[500];
  SQLLEN cbLeft;      // #bytes remained

  while ((SQL_SUCCEEDED(SQLGetData(StmtHandle, 
                                   colnum, 
                                   SQL_C_BINARY, 
                                   buf, 
                                   sizeof(buf),
                                   &cbLeft))))
  //                               ^^^^^^^
  {
          string data(reinterpret_cast< const char* >(buf),
                      reinterpret_cast< const char* >(buf)
                      + cbLeft);
          //            ^^^^^^
          str = str + data;

Please take a few minutes to review Using Length/Indicator Values in order to check how the length/indicator value is used.

查看更多
登录 后发表回答