English Español Български

How to Store and Retrieve an Image or File with SQLite

Images or any files can be stored in a database. Here is one way to do it using the following steps:

1. Read the system file into a QByteArray.
2. Store QByteArray as a Binary Large Object in database.

For example :

  1.  
  2.     QFile file(fileName);
  3.     if (!file.open(QIODevice::ReadOnly)) return;
  4.     QByteArray byteArray = file.readAll();
  5.  
  6.     QSqlQuery query;
  7.     query.prepare("INSERT INTO imgtable (imgdata) VALUES (?)");
  8.     query.addBindValue(byteArray);
  9.     query.exec();

Now, the image/file can be retrieved like any other data

  1.     QSqlQuery query("SELECT imgdata FROM imgtable");
  2.     query.next();
  3.     QByteArray array = query.value(0).toByteArray();

Creating a QPixmap from QByteArray :

  1.     QPixmap pixmap = QPixmap();
  2.     pixmap.loadFromData(array);

It is done. Now the pixmap can be used in a Button as icon or in label etc.

Categories: