2014-01-20 62 views
0

我有一个Insert函数,它打开图像文件并插入到数据库中。读取C++中的二进制数据并写入MySQL

void insertBlob() 
{ 
     sql::Driver *driver; 
     sql::Connection *con; 
     sql::PreparedStatement *pstmt; 

    ifstream file ("/home/malper/NetBeansProjects/BlobTesting/2", ios::in | ios::binary | ios::ate); 
     ifstream::pos_type fileSize; 
     char* fileContents; 

     char buff[1024]; 


     if(file.is_open()) 
     { 
      fileSize = file.tellg(); 
      fileContents = new char[fileSize]; 
      file.seekg(0, ios::beg); 
      if(!file.read(fileContents, fileSize)) 
      { 
       cout << "fail to read" << endl; 
      } 


      file.close(); 
     } 
     istringstream str(fileContents); 

     ///////////////////////////////////////////////// 

     /* Create a connection */ 
     driver = get_driver_instance(); 
     con = driver->connect("tcp://192.168.2.5:3306", "root", "root"); 

     /* Connect to the MySQL test database */ 
     con->setSchema("test"); 

     pstmt=con->prepareStatement("INSERT INTO Dao VALUES(57,4,'2014-12-23 11:55:54',?,1,1)"); 

     pstmt->setBlob(1,&str); 
     pstmt->executeUpdate(); 

} 

数据库部分工作正常,但打开文件后我无法将二进制图像转换为字符串流。我如何在这个函数中存储二进制字符串?

回答

0

std::stringstream constructor需要一个std :: string作为参数。这可以从文件内容:

std::string tempContent(fileContents, fileSize); 
std::stringstream str(tempContent); 

它仍然感到很奇怪,因为字符串不处理二进制数据。

+0

std :: stringstream str(tempContent); – Duke

+0

@jekyll:谢谢,纠正。 – stefaanv

0

您需要的是二进制数据的ASCII表示。

幸运的是,您不必打个盹,Base64是标准格式。

来自Base64来回数据转换的解决方案很容易获得: This应该是一个好的开始。