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!


Qt Code:
  1. QByteArray toByarray( const QVector<float>& data )
  2. {
  3. QByteArray result;
  4. QDataStream bWrite( &result, QIODevice::WriteOnly );
  5. bWrite << data;
  6.  
  7. return result;
  8.  
  9. }
  10.  
  11. QVector<float> toVectorF( const QByteArray& buffer )
  12. {
  13. QVector<float> result;
  14. QDataStream bRead( buffer );
  15. bRead >> result;
  16.  
  17. return result;
  18.  
  19. }
  20.  
  21. int saveToDB( const QVector<float>& vec )
  22. {
  23. QSqlQuery query( db );
  24.  
  25. query.prepare( "insert into MyTable ( array ) values ( ? )" );
  26. query.bindValue( 0, toByarray( vec ) );
  27.  
  28. int id( -1 );
  29. if ( query.exec() ) {
  30. id = query.lastInsertId().toInt();
  31. }
  32.  
  33. return id;
  34. }
  35.  
  36. QVector<float> readFromDB( int id )
  37. {
  38. QSqlQuery query( db );
  39.  
  40. query.prepare( "select array from MyTable where id=?" );
  41. query.bindValue( 0, id );
  42.  
  43. QVector<float> result;
  44. if ( query.exec() && query.next() ) {
  45. result = toVectorF( query.value( 0 ).toByteArray() );
  46. }
  47.  
  48. return result;
  49. }
To copy to clipboard, switch view to plain text mode