PDA

View Full Version : how to save QVector<float> into sqlite as BLOB?



lni
2nd April 2016, 15:08
Hi,

I am trying to save QVector<float> into database as a BLOB field, but I am not getting the data back correctly. Here is the code.

Can anyone please tell me what is the problem?

Many thanks!





QByteArray toByarray( const QVector<float>& data )
{
QByteArray result;
QDataStream bWrite( &result, QIODevice::WriteOnly );
bWrite << data;

return result;

}

QVector<float> toVectorF( const QByteArray& buffer )
{
QVector<float> result;
QDataStream bRead( buffer );
bRead >> result;

return result;

}

int saveToDB( const QVector<float>& vec )
{
QSqlQuery query( db );

query.prepare( "insert into MyTable ( array ) values ( ? )" );
query.bindValue( 0, toByarray( vec ) );

int id( -1 );
if ( query.exec() ) {
id = query.lastInsertId().toInt();
}

return id;
}

QVector<float> readFromDB( int id )
{
QSqlQuery query( db );

query.prepare( "select array from MyTable where id=?" );
query.bindValue( 0, id );

QVector<float> result;
if ( query.exec() && query.next() ) {
result = toVectorF( query.value( 0 ).toByteArray() );
}

return result;
}

ChrisW67
2nd April 2016, 21:51
What is not correct about what you get back?
Do you have a valid id to retrieve? Does your insert succeed? Does your insert return a valid id? Does the id overflow an int?

lni
3rd April 2016, 05:45
It creates a record in the table as I can see using sqlitebrowser and returns a valid id.

I use that id to read back the BLOB data, and convert back to QVector<float>, the vector length is correct, but the content is wrong.

The QVector I save is
QVector(0, 41.41, 69.29, 98.1, 126.92, 155.77, 184.64, 213.48, 242.15, 271.06)

But when I read back and convert back to QVector, I get:
QVector(0, 0.59, 0.75, 1.09, 1.5, 1.7, 1.83, 2.13, 2.15, 1.89)

lni
3rd April 2016, 07:59
Problem solved.

It is stupid that the sql statement missing a commas.