PDA

View Full Version : Read BLOB from MySQL database



zero-n
22nd May 2011, 16:19
I want to read the BLOB field in my table to reconstruct the image save there my problem is that can't retrieve the value of BLOB from db to (bytes) which is (QByteArray).

This is my code:


void Dialog::RetrieveFromDatabase()
{
QString imagePath = QFileDialog::getSaveFileName(this,"Save image to",QDir::currentPath(),"JPEG Image (*.jpg)");

QSqlQuery query;
query.prepare("SELECT image FROM `test`.`images` WHERE `id_no`=':id';");
query.bindValue(":id",ui->lineID->text());
if (!query.exec())
{
QMessageBox::critical(this,"Query error",query.lastError().text());
}
else
{
//Load image form database
QByteArray bytes = query.value(query.record().indexOf("image")).toByteArray();

//Save image to disk
QImage imageWrite;
imageWrite.loadFromData(bytes,"JPG");
imageWrite.save(imagePath,"JPG");
}
}

tinysoft
22nd May 2011, 17:16
see this link (http://dev.mysql.com/doc/refman/5.1/en/blob.html) ... it contain example that may help you

or u can use this code :


QModelIndex index;
QSqlQueryModel model;

query.exec("select image FROM images where id_no=1;");
model.setQuery(query);

index = model.index(0,0);

QByteArray ba1 = index.data().toByteArray();
QPixmap pic;
pic.loadFromData( ba1);

pic.save(imagePath,"JPG");

zero-n
22nd May 2011, 17:48
my problem is that (bytes) is empty after running this function but i don't know why.

i have another function that saved images into my database that works correctly, and i am pretty sure that there is no problem with MySQL database.

zero-n
22nd May 2011, 19:59
Thanks for tinysoft now my code is working well.



void Dialog::RetrieveFromDatabase()
{
QString imagePath = QFileDialog::getSaveFileName(this,"Save image to",QDir::currentPath(),"JPEG Image (*.jpg)");
QModelIndex index;
QSqlQueryModel model;
QByteArray bytes;

QSqlQuery query;
query.prepare("SELECT image FROM `test`.`images` WHERE `id_no`=:id;");
query.bindValue(":id",ui->lineID->text());
if (!query.exec())
{
QMessageBox::critical(this,"Query error",query.lastError().text());
}
else
{
//Set model
model.setQuery(query);
index = model.index(0,0);
bytes = index.data().toByteArray();

//Save image
QImage imageWrite;
imageWrite.loadFromData(bytes);
imageWrite.save(imagePath,"JPG");

}
}