MySQL Forums
Forum List  »  Connector/C++

Is there an example using a Blob ?
Posted by: Jean-Denis Muys
Date: September 22, 2009 02:40AM

Hi,

As far as I can see, none of the examples for Connector/C++ demonstrate how to send and/or receive a blob to/from mySQL.

Where could I find such an example?

The difficulty to me stems from the fact that sending a blob involves a std::istream:

virtual void PreparedStatement:setBlob(unsigned int parameterIndex, std::istream * blob);

And given a blob in memory (an opaque block whose origin could be, say, malloc), I have a hard time making a std::istream out of it, in a way that does NOT imply copying the memory block.

Here is what I tried, questions follow:

std::string insertSQL = "INSERT INTO RKTable (RKBlob, RKModifStamp) VALUES (?, now())";
std::auto_ptr<sql::PreparedStatement> prep_stmt(this->_mySQL->prepareStatement(insertSQL));

size_t packageLength;
void * package;
while ((package = getNextPackage(&packageLength)) != NULL) {

try {
std::strstream tmp_blob(static_cast<char *> (package), packageLength);
prep_stmt->setBlob(1, &tmp_blob);
int num_rows = prep_stmt->executeUpdate();
tmp_blob.freeze(true);
log << "insert into mySQL affected " << num_rows << endl;
} catch (...) { snip exception processing }

free(package);
}

I am very nervous using std::strstream as a class as the char * streams are deprecated, but I could not find a way using any other standard stream class.

Note that, as documented, you can't rely on the char * stream to release the memory buffer. That's why I have my call to free. Of course, I know that getNextPackage allocated using malloc().

Since I want to free the blob myself, I need to freeze the stream. Otherwise, the stream thinks it manages the memory itself.

Since the istrstream doesn't have a freeze function, I use a strstream.

Note also that the stream is constructed and destructed every time through the loop. This might be a little wasteful, but should not be otherwise detrimental.

Here are my questions:

- Has anybody some working code to share that works with blobs?
- Is memory managed correctly in this code snippet, as far as the stream is concerned?
- How would I modify the snipped to construct and destruct the stream only once?
- Is there a workable way to change this snippet to use a istrstream instead?
- Is there a way to use not-deprecated stream class instead?

Thanks for any comment.

Options: ReplyQuote


Subject
Views
Written By
Posted
Is there an example using a Blob ?
8905
September 22, 2009 02:40AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.