How to set binary data using setBlob() in C++ connector

倾然丶 夕夏残阳落幕 提交于 2019-12-23 03:17:10

问题


I know this has been asked before, and I tried to implement the solution, but I just get exception errors when I call ps->executeUpdate(). Has anyone got an explicit example?


回答1:


Sorry Matthew - I assumed the previous answer to this question (by elrohin). Maybe I should have replied to that. Anyway heres the code he suggested:

class DataBuf : public streambuf
{
public:
   DataBuf(char * d, size_t s) {
      setg(d, d, d + s);
   }
};


// prepare sql update statement etc. and set the data pointer
string* pData = ; // ...not part of the original answer

DataBuf buffer((char*)pData->data(), pData->length());
istream stream(&buffer);
ps->setBlob(1, &stream);
ps->executeUpdate(); // This causes an exception in free.c

I'm using VS9 with the latest (beta) connector/cpp debug libs. I've also tried using char* instead of string.




回答2:


This code works fine for me:


  Driver *driver;
  Connection *conn;

  driver = get_driver_instance();
  conn = driver->connect("tcp://127.0.0.1:3306", "root", "root");

  std::auto_ptr use_stmt(conn->createStatement());
  use_stmt->execute("USE world");

  std::auto_ptr stmt(conn->prepareStatement("INSERT INTO terrain_texture_tiles_0 (data) VALUES(?)"));
  std::string value("A\0B", sizeof("A\0B") - 1);
    std::istringstream tmp_blob(value);
    stmt->setBlob(1, &tmp_blob);
    stmt->execute(); 

hope it helps ... Jaroslav Pribyl




回答3:


This post is a bit old, but I ran across the same question. I employed the method above and it didn't quite work right for my case, which was trying to take a vector and use that for the stream. What I was doing was taking a UUID and converting it into a 16 byte binary version to use in the table. Using the method above, I found that only half my buffer was being populated.

I ended up using a stringstream.

std::vector<unsigned char>  convertedId;
std::stringstream           stream;

// convertedId has been populated with the 16 byte binary version
stream = std::stringstream(std::string(convertedId.begin(), convertedId.end()));
// Parameter 1 is BINARY(16)
pStatement->setBlob(1, &stream);

A few other things to keep in mind. The stream is not accessed until one of the execute variants is called. So you'll need to keep the stream around until you have run execute.

Hopefully this will help someone and save them time.



来源:https://stackoverflow.com/questions/1108700/how-to-set-binary-data-using-setblob-in-c-connector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!