【问题标题】:Read and write image(large object) from postgres with qt使用 qt 从 postgres 读取和写入图像(大对象)
【发布时间】:2019-09-17 02:17:45
【问题描述】:

我想在带有 oid 类型和框架 qt 的 postgres 中读取和写入像图像或视频这样的大对象。在查询中,我可以使用 lo_import 和 lo_export 读取和写入具有特定本地地址的大型对象以进行导入和导出。但问题是如何使用 qt 和 qsqlquery 进行读写?

【问题讨论】:

    标签: c++ postgresql qt blob large-data


    【解决方案1】:

    假设您有一个名为 "my_table" 的表。为了使用 PostgreSQL 存储大型二进制对象,建议使用 bytea 类型作为数据字段,因此将其命名为 "binary_data"

    要插入数据,我会使用QSqlRecord,如下所示:

    QSqlTableModel *model;
    QSqlDatabase m_database;
    m_database = ...//connect to the database here
    model = new QSqlTableModel(0, m_database);
    model->setTable("my_table");
    model->select();
    QSqlRecord rec;
    rec = model->record();
    QFile f("path_to_a_big_file");
    if(f.open(QIODevice::ReadOnly))
    {
        QByteArray ba = f.readAll();
        rec.setValue("binary_data",ba.toBase64());
    }
    model->insertRecord(-1,rec);
    model->submitAll();
    

    要更新数据QSqlQuery 会这样做:

    QSqlQuery query(m_database);
    query.prepare("update my_table set binary_data = :binary_data where [condition]....");
    QFile f("path_to_a_big_file");
    if(f.open(QIODevice::ReadOnly))
    {
        QByteArray ba = f.readAll();
        query.bindValue(":binary_data",ba.toBase64());
    }
    query.exec();
    

    最后要读取数据,您需要执行以下操作:

    QSqlTableModel *model;
    model = new QSqlTableModel(0, m_database);
    model->setTable("my_table");
    model->select();
     while(model->canFetchMore())
        model->fetchMore();
    for (int i = 0; i < model->rowCount(); ++i)
    {
        QByteArray ba = QByteArray::fromBase64(model->record(i).value("binary_data").toByteArray())
        //do something with the retrieved data
    }
    

    另请注意,您有责任记住您放入表格中的文件类型。

    【讨论】:

      【解决方案2】:

      您可以将server side SQL functions 用于大型对象,可通过SELECT 语句通过QSqlQuery::exec() 调用。

      要一次性读取或写入大型对象,请参阅 lo_getlo_put

      如果二进制数据足够大以至于您宁愿分块处理它们,请启动事务,然后在循环中使用lo_openloread/lowritelo_close...

      发送和检索的二进制数据的PostgreSQL类型是bytea。与QSqlQuery绑定输入参数时应使用QSql::Binary,以便驱动程序在需要时相应地转义数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-13
        • 1970-01-01
        • 2012-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-20
        • 1970-01-01
        相关资源
        最近更新 更多