简单的code如下:
#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(NULL == mysql_init(&conn)) { cerr << "init conn fail." << endl; exit(-1); } if (NULL == mysql_real_connect(&conn, host, username, password, dbname, 0, NULL, 0)) { cerr << "connect to database error" << endl; exit(-1); } char sql[] = "select octet_length(picture), picture from tablename"; if (0 != mysql_real_query(&conn, sql, strlen(sql))) { cerr << "query error." << endl; exit(-1); } MYSQL_RES * result = NULL; result = mysql_store_result(&conn); if (NULL == result) { cerr << "store result error." << endl; exit(-1); } if (0 >= mysql_affected_rows(&conn)) { cerr << "no data be found." << endl; exit(-1); } int count = 0; string path = "/home/tsfh/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(0 == size ) { cerr << "invalid record!" << endl; continue; } temp_buff = (char *)malloc(size * sizeof(char) + 1); if(NULL == temp_buff) { 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; }