远程从数据库提取图片

本文使用的是mysql的 mysql-connector-c++ 

图片是以二进制形式保存在数据库中,将图片从数据库中提取出来保存到本地。

代码如下:

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


string path = "D:\\data\\test\\";


int main()
{
	const char username[] = "root";
	const char password[] = "***";
	const char host[] = "192.168.1.1";
	const char dbname[] = "test";
	unsigned int port = 3306;


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


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


	char sql[] = "select octet_length(pic), pic from face_check_history";
	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 (!result)
	{
		cerr << "store result error." << endl;
		exit(-1);
	}


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


	MYSQL_ROW row_record;
	int count = 0;
	while (row_record = mysql_fetch_row(result))
	{
		unsigned int size = 0;
		char * temp_buff = NULL;


		sscanf(row_record[0], "%d", &size);
		temp_buff = (char *)malloc(size * sizeof(char)+1);
		if (temp_buff == NULL)
		{
			printf("malloc error!\n");
			exit(1);
		}


		if ((0 == size) || (NULL == row_record[1]))
		{
			cerr << "invalid record!" << endl;
			continue;
		}
		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);
}

猜你喜欢

转载自blog.csdn.net/ywj541726330/article/details/80183210