[英]Read and write image(large object) from postgres with qt
I want to read and write large object like image or video in postgres with oid type with framework qt. 我想在带有框架qt的oid类型的postgres中读取和写入像图像或视频这样的大对象。 In query i can using lo_import and lo_export to read and write largeobject with specific local address for import and export. 在查询中,我可以使用lo_import和lo_export来读取和写入具有特定本地地址的大对象以进行导入和导出。 But question is how can i read and write with qt and qsqlquery? 但问题是如何用qt和qsqlquery读写?
You may use the server side SQL functions for large objects, callable by SELECT
statements through QSqlQuery::exec()
. 您可以将服务器端SQL函数用于大对象,可以通过QSqlQuery::exec()
通过SELECT
语句调用。
To read or write a large object in one go, see lo_get
and lo_put
. 要一次读取或写入大对象,请参阅lo_get
和lo_put
。
If the binary data are large enough that you'd rather process them by chunks, start a transaction, then use lo_open
, loread
/ lowrite
in a loop, lo_close
... 如果二进制数据是足够大的,你宁愿用块处理它们,启动一个事务,然后用lo_open
, loread
/ lowrite
在一个循环中, lo_close
...
The PostgreSQL type of the binary data sent and retrieved is bytea
. 发送和检索的二进制数据的PostgreSQL类型是bytea
。 QSql::Binary
should be used when binding input parameters with QSqlQuery
, for the driver to escape the data accordingly when needed. 当使用QSqlQuery
绑定输入参数时,应使用QSql::Binary
,以便驱动程序在需要时相应地转义数据。
Let's assume you have a table named "my_table" . 假设您有一个名为“my_table”的表。 For storing large binary objects with PostgreSQL it is recommended to use bytea
type for a datafield, so name it "binary_data" . 对于使用PostgreSQL存储大型二进制对象,建议对数据字段使用bytea
类型,因此将其命名为“binary_data” 。
To insert data I'd use QSqlRecord
, like this: 要插入数据我会使用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();
To update the data QSqlQuery
will do: 要更新数据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();
And finally to read the data you'll need to do something like this: 最后要阅读你需要做的事情:
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
}
Also note that it is your responsibility to remember the type of a file you put inside the table. 另请注意,您有责任记住放在表格中的文件类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.