The whole code is:
// https://stackoverflow.com/questions/18092240/sqlite-blob-insertion-c
int InsertFile(const string& db_name, const string &file_name)
{
ifstream file(file_name.c_str(), ios::in | ios::binary);
if (!file) {
cerr << "An error occurred opening the file\n";
return 12345;
}
file.seekg(0, ifstream::end);
streampos size = file.tellg();
file.seekg(0);
char* buffer = new char[size];
file.read(buffer, size);
sqlite3* db = NULL;
int rc = sqlite3_open_v2(db_name.c_str(), &db, SQLITE_OPEN_READWRITE, NULL);
if (rc != SQLITE_OK) {
cerr << "db open failed: " << sqlite3_errmsg(db) << endl;
}
else {
sqlite3_stmt* stmt = NULL;
rc = sqlite3_prepare_v2(db,
"INSERT INTO DEMO_TABLE(DEMO_FILE)"
" VALUES(?)",
-1, &stmt, NULL);
if (rc != SQLITE_OK) {
cerr << "prepare failed: " << sqlite3_errmsg(db) << endl;
}
else {
// SQLITE_STATIC because the statement is finalized
// before the buffer is freed:
rc = sqlite3_bind_blob(stmt, 1, buffer, size, SQLITE_STATIC);
if (rc != SQLITE_OK) {
cerr << "bind failed: " << sqlite3_errmsg(db) << endl;
}
else {
rc = sqlite3_step(stmt);
if (rc != SQLITE_DONE)
cerr << "execution failed: " << sqlite3_errmsg(db) << endl;
}
}
sqlite3_finalize(stmt);
}
sqlite3_close(db);
delete[] buffer;
}
int retrieve_file(const string& db_name, const string& file_name)
{
sqlite3* db;
sqlite3_stmt* stmt;
const char* sql = "SELECT demo_file FROM demo_table WHERE ID = ?";
int rc = sqlite3_open(db_name.c_str(), &db);
if (rc)
{
std::cerr << "Can't open database: " << sqlite3_errmsg(db) << std::endl;
return rc;
}
rc = sqlite3_prepare_v2(db, sql, -1, &stmt, nullptr);
if (rc != SQLITE_OK) {
std::cerr << "Failed to prepare statement: " << sqlite3_errmsg(db) << std::endl;
sqlite3_close(db);
return rc;
}
int param_value = 1; // Example value
sqlite3_bind_int(stmt, 1, param_value);
rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
const void* blob = sqlite3_column_blob(stmt, 0);
int blob_size = sqlite3_column_bytes(stmt, 0);
std::vector<unsigned char> blobData((unsigned char*)blob, (unsigned char*)blob + blob_size);
ofstream f(file_name.c_str(), ios_base::binary);
f.write(reinterpret_cast<char*>(&blobData[0]), blobData.size() * sizeof(unsigned char));
f.close();
}
else if (rc == SQLITE_DONE) {
std::cout << "No rows found." << std::endl;
}
else {
std::cerr << "Failed to step statement: " << sqlite3_errmsg(db) << std::endl;
}
sqlite3_finalize(stmt);
sqlite3_close(db);
return 0;
}
int main(int argc, char** argv)
{
//string filename = "";
//if(openFileDialog(filename))
// cout << filename << endl;
//InsertFile("test.db", "C:/temp/1.png");
int x = retrieve_file("test.db", "C:/temp/1_out.png");
cout << x << endl;
return 0;
}