[英]Read Binary Data in C++ and Write to 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();
}
数据库部分工作正常,但是打开文件后我无法将二进制图像发送到stringstream。 如何在此函数中将二进制文件存储在字符串中?
std :: stringstream构造函数期望将std :: string作为参数。 这可以通过filecontent来实现:
std::string tempContent(fileContents, fileSize);
std::stringstream str(tempContent);
仍然感觉很奇怪,因为没有将字符串用于处理二进制数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.