C program to insert an image data into SQLite table

Here, we are going to write a C program to insert an image data into SQLite table.
By Nidhi Last updated : March 10, 2024

Prerequisites

The following packages need to be installed in the ubuntu machine for Sqlite connectivity using the C program.

sudo apt install sqlite3
sudo apt install gcc
sudo apt install libsqlite3-dev

Problem Solution

In this program, we will read data from an image file and then insert image data into the database table. Here, we need to create a table before executing the program using the below statement.

sqlite> CREATE TABLE Images(Id INTEGER PRIMARY KEY, Data BLOB);

Program/Source Code

The source code to insert image data into the SQLite table in Linux is given below. The given program is compiled and executed successfully on Ubuntu 20.04.

//C program to insert an image into SQLITE table.

#include <sqlite3.h>
#include <stdio.h>

int main()
{
    int imageLen = 0;
    int ret = 0;

    char* errMsg = 0;
    FILE* fptr = fopen("sample.jpg", "rb");
    sqlite3* db_ptr;
    sqlite3_stmt* stmt;

    if (fptr == NULL) {
        printf("Cannot open image file\n");
        return 1;
    }

    fseek(fptr, 0, SEEK_END);
    imageLen = ftell(fptr);
    fseek(fptr, 0, SEEK_SET);

    char imageData[imageLen + 1];

    fread(imageData, 1, imageLen, fptr);
    fclose(fptr);

    ret = sqlite3_open("MyDb.db", &db_ptr);

    if (ret != SQLITE_OK) {
        printf("Cannot open database file\n");
        sqlite3_close(db_ptr);
        return 1;
    }

    char* query = "INSERT INTO Images(Data) VALUES(?)";

    ret = sqlite3_prepare(db_ptr, query, -1, &stmt, 0);

    if (ret != SQLITE_OK) {
        printf("Cannot prepare SQL statement\n");
        return 1;
    }

    sqlite3_bind_blob(stmt, 1, imageData, imageLen, SQLITE_STATIC);

    ret = sqlite3_step(stmt);

    if (ret != SQLITE_DONE)
        printf("execution failed: %s", sqlite3_errmsg(db_ptr));

    sqlite3_finalize(stmt);
    sqlite3_close(db_ptr);

    printf("Image inserted successfully\n");

    return 0;
}

Output

$ gcc insert_image.c -o insert_image -lsqlite3 -std=c99
$ ./insert_image
Image inserted successfully

In the above program, we included the sqlite3.h header file to uses SQLite related functions. Here, we inserted an image into the Images table in the "MyDb.db" database. Here, we read image data from an image file and then insert that image data into the database table. Here, we printed the "Image inserted successfully" message on the console screen on successful insertion of the image.

C SQLite Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.