qsqlite 存储和展示一个blob字段的数据

qsqlite存储一个blob字段

第一种,通过直接使用sql语句进行存储:


    sql = QString("INSERT INTO phone_video_fragment_display (_id,thumbnail,name,video_fragment_id) VALUES(%1,:thumbnail,'%2',%3);")
                  .arg(i64_phone_video_fragment_display_max_id)
                  .arg("demo....")
                  .arg(i64_phone_video_fragment_max_id);
    query.prepare(sql);
        //示例图片
    QFile o_demo_jpeg("demo.jpg");
    auto open_result = o_demo_jpeg.open(QIODevice::ReadOnly);
    auto ba_demo_jpeg = o_demo_jpeg.readAll();
    query.bindValue(":thumbnail",ba_demo_jpeg);
    qDebug() << query.boundValues();
    auto exe_result = query.exec();
    auto error = query.lastError();
    qDebug() << error.text();

如上将thumbnail 图片存入数据库


第二种,通过更上层的接口

QSqlTableModel提供的insertRecord

(QSqlTableModel关联一个数据库的一张表,对其进行显示或者操作)

    QSqlRecord record;
    QSqlField _id("_id",QVariant::LongLong);
    _id.setValue(i64_phone_video_fragment_display_max_id);
    QSqlField image("thumbnail",QVariant::ByteArray);
    image.setValue(ba_demo_jpeg);
    QSqlField name("name",QVariant::String);
    name.setValue(QString::number(i64_phone_video_fragment_display_max_id));
    QSqlField video_fragment_id("video_fragment_id",QVariant::LongLong);
    video_fragment_id.setValue(i64_phone_video_fragment_max_id);
    record.append( _id );
    record.append( image );
    record.append( name );
    record.append( video_fragment_id );
 
 
    this->m_p_obj_phone_video_fragment_model->insertRecord( -1,record );
    this->m_p_obj_phone_video_fragment_model->select();


别忘了select提交所有更改并刷新ui


要展示一个blob字段,如上的图片,我们需要自己子类化一个delegate的paint接口

void CPhoneVideoFragmentDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    //列说明:0._id,1.图片,2.名字,3.底层的视频碎片id
    if(index.column() == 1)
    {
        auto ba_image = index.model()->data(index).toByteArray();
        auto image = QImage::fromData(ba_image);
        painter->drawImage(option.rect,image);
    } else {
        return (QStyledItemDelegate::paint(painter,option,index));
    }
    return ;
}

你可能感兴趣的:(qsqlite 存储和展示一个blob字段的数据)