0

I have an Insert function which opens image file and inserts to database.

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();

}

Database part works well but i can't get binary image to stringstream after open file. How can i store binary in a string in this function?

Ulfsark
  • 902
  • 1
  • 11
  • 26

2 Answers2

0

The std::stringstream constructor expects a std::string as argument. This could be made from the filecontent:

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

It still feels weird because strings are not made to handle binary data.

stefaanv
  • 14,072
  • 2
  • 31
  • 53
0

What you need is an ASCII representation of binary data.

Fortunately you don't have to make one up, Base64 is a standard format.

Solutions for converting data back and forth from Base64 is readily available : This should be a good start.

Community
  • 1
  • 1
jlouzado
  • 442
  • 3
  • 17