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


Guide

create table

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++.

std::shared_ptr<char> Image;

insert

sql

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

code

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

SELECT id, camera_id, image FROM camera;

code

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.

Author: kezunlin
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint polocy. If reproduced, please indicate source kezunlin !
评论
  TOC