0%

how to store image longblob with mysql cpp connector in c++

Guide

create table

1
2
3
4
5
CREATE TABLE IF NOT EXISTS `camera` (\
`id` int(11) NOT NULL AUTO_INCREMENT,\
`camera_id` tinyint(4) UNSIGNED NOT NULL,\
`image` longblob NOT NULL,\
`create_time` datetime NOT NULL)

camera.Image of type in c++.

1
std::shared_ptr<char> Image;

insert

sql

1
INSERT INTO camera(camera_id, image) VALUES(? , ? );

code

1
2
3
4
5
6
7
8
9
10
11
12
13
struct membuf : std::streambuf {
membuf(char* base, std::size_t n) {
this->setg(base, base, base + n);
}
};

// get blob istream
char *buffer = camera.Image.get();
size_t size = camera.ImageLength;
membuf mbuf(buffer, size);
std::istream blob(&mbuf); // must be local variable

pstmt->setBlob(6, &blob);

select

sql

1
SELECT id, camera_id, image FROM camera;

code

1
2
3
4
5
std::istream *blob = res->getBlob("image");
size_t size = res->getUInt("image_length");
auto ptr_buffer = Util::get_buffer_from_stream(blob, size);

camera.Image = ptr_buffer;

Reference

History

  • 20180123: created.