2014-01-20 61 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應該是一個好的開始。