It is necessary to build database Blob field by using Qbytearray to make it easy to use its API to access and modify memory data. How to write custom structures and classes into blobs
1. Copy memory data with memcpy
//Custom person struct CPP code typedef struct { int age; char name[20]; }person; //write multiple structures to Qbytearray void writestruct () { QByteArray ba; ba.resize (2*sizeof (person)); //Set capacity //serialization for (Int i=0;i <2;i++) { person p1; p1.age=10+i; strcpy (P1.name, "Javaeye"); memcpy (Ba.data () +i*sizeof (person), &p1,sizeof (person)), //pointer movement, writing multiple Data } //Restore Data person *person= (person*) Ba.data (); qdebug () <<person->age<< "---" <<person-> name; person++; qdebug () < <person->age<< "---" <<person->name; }
memcpy can only handle fields as basic type of struct, when using qstring name, I use Person->name to access its value, program crashes; This shows that the memory data cannot be restored and built into the Qstring class. If you want to write a custom QT class, you can only use Qbuffer to write to the binary stream
2. Qbuffer writing QT Custom structure CPP code //qbuffer serializing Custom Objects typedef struct { int age; QString name; } qperson; /** * @brief Overloading the input of custom objects */ inline qdatastream &operator<< (Qdatastream &out,const qperson &per) { out<<per.age<<per.name; return out; } /** * @brief Overloading the output of custom objects */ inline qdatastream &operator>> (Qdatastream &in,qperson &per) { int age; qstring name; in>>age>>name; &NBsp; per.age=age; per.name=name; return in; } /** * @brief Qbuffer can handle QT custom types */ void testqbuffer () { QByteArray ba; ba.resize (2*sizeof (Qperson)); qbuffer buffer (&BA); buffer.open ( qiodevice::writeonly); //input Qdatastream out (&buffer); for (int i=0;i<2;i++) { QPerson per; per.age=20+i;