将图像作为blob类型插入QT C++中的数据库

inserting an image as a blob type to database in QT C++

本文关键字:C++ QT 数据库 插入 类型 图像 blob      更新时间:2023-10-16

从计算机中选择图像后,我正试图将图像作为blob类型插入数据库。我有两个按钮。一种是选择图像。另一个按钮是将图像添加到数据库

选择按钮

// to get an image stored in pc to a qlabel
void EducationSection::on_btnChse_clicked()
{
QString imageFile = QFileDialog ::getOpenFileName(0,"Select Image","/home/","Image Files (*.png)");
  QFileInfo info(imageFile);
  filename = info.fileName();
  QPixmap image (imageFile);
  ui->lblBkImge->setPixmap(image);
  ui->lblBkImge->show();
}

添加按钮

void EducationSection::on_btnAdd_2_clicked()
{
    QByteArray byte;
    QFile file(filename);
    if(file.open(QIODevice::ReadOnly))
    {
        byte = file.readAll();
        file.close();
    }
    QMessageBox :: critical(this,"Error",filename);
    QSqlQuery query;
    query.prepare("insert into eduimage(image) values (:image)");
    query.bindValue(":image",byte);
    if(query.exec())
    {
         QMessageBox :: information(this,"Save","Data Inserted successfully", QMessageBox ::Ok);
    }
    else
    {
         QMessageBox :: critical(this,"Error","Couldn't insert data");
    }
}

这里filename是一个局部变量。一旦选择了图像,它就会根据需要显示在标签中。但数据并没有插入。尽管我试图解决这个问题,但我做不到。请帮帮我。提前谢谢你。

我以前在MySQL数据库中遇到过这个问题。我解决这个问题的方法是明确指定绑定类型必须是原始二进制数据。

在你的情况下,试试

query.bindValue(":image", byte, QSql::In | QSql::Binary);