C++ 获取mysql数据库以blob类型储存的图片

最近遇到个用C++代码取出以blob类型存放在mysql数据库里面图片的需求, 粗略的翻了翻mysql的api文档, 写了个最简单的实现:

#include <iostream>
#include <fstream>
#include <sstream>
#include <cstring>
#include <mysql/mysql.h>
using namespace std;

int main()
{
const char username[] = "username";
const char password[] = "password";
const char host[] = "192.168.0.100";
const char dbname[] = "dbname";

MYSQL conn;
if(mysql_init(&conn) == nullptr) {
cerr << "init conn fail." << endl;
exit(-1);
}

if (mysql_real_connect(&conn, host, username, password, dbname, 0, NULL, 0) == nullptr) {
cerr << "connect to database error" << endl;
exit(-1);
}

char sql[] = "select octet_length(picture), picture from tablename";
if (mysql_real_query(&conn, sql, strlen(sql)) != 0) {
cerr << "query error." << endl;
exit(-1);
}

MYSQL_RES * result = NULL;
result = mysql_store_result(&conn);
if (result == nullptr) {
cerr << "store result error." << endl;
exit(-1);
}

if (mysql_affected_rows(&conn) <= 0) {
cerr << "no data be found." << endl;
exit(-1);
}

int count = 0;
string path = "/home/sakuragl/pictures/";
MYSQL_ROW row_record;
while (row_record = mysql_fetch_row(result)) {
unsigned int size = 0;
char * temp_buff = NULL;

sscanf(row_record[0], "%d", &size);
if(size == 0) {
cerr << "invalid record!" << endl;
continue;
}

temp_buff = (char *)malloc(size * sizeof(char) + 1);
if(temp_buff == nullptr) {
cerr << "malloc error!" <<endl;
exit(1);
}
memset(temp_buff, 0, size * sizeof(char) + 1);
memcpy(temp_buff, row_record[1], size * sizeof(char));

stringstream pic_name;
pic_name << count << ".jpg";
ofstream outfile(path + pic_name.str(), ios::binary);
outfile.write(temp_buff, size);

count++;
free(temp_buff);
}

mysql_close(&conn);
return 0;
}