Introduction
I had to store rows of several fairly large multidimensional numerical arrays in a SQLSERVER database. These data must be exportable from there to a mySQL database as well. Since it is absolutely impossible (and fortunately not necessary) to have a separate column for each value, I decided to store them as a blob.
Background
Although this is not a big problem using ODBC, I did not find explicit examples of how to do this using C++ and ADO anywhere (perhaps my fault...).
Using the Code
All arrays/variables in question are serialized into a single unsigned
char
array using memcpy
which is copied into a SAFEARRAY
afterwards.
The SAFEARRAY
is attached to a _variant_t
variable of type VT_ARRAY
| VT_UI1
.
This _variant_t
variable can now be stored in a varbinary(MAX)
column in a SQLSERVER database using the ADO PutValue
method:
unsigned char *U=new unsigned char[no_of_Bytes]; memcpy(&U[0],myArray,no_of_Bytes);
SAFEARRAY *SA=SafeArrayCreateVector(VT_UI1,0,no_of_Bytes);
long ix[1]; for (int i=0;i<no_of_Bytes;i++)
{
ix[0]=i; SafeArrayPutElement(SA,ix,&U[i]);
}
_variant_t *V=new _variant_t();
V->vt=VT_ARRAY|VT_UI1; V->parray=SA;
outrecordset->AddNew(); outrecordset->Fields->GetItem("col_name")->PutValue(V); outrecordset->UpdateBatch(adAffectAll);
delete [] U; SafeArrayDelete(SA);
V->parray=NULL; delete V;
Of course, instead of arrays, any binary data that fits into the varbinary
(MAX
) size limit can be handled like this. Reading the data from the database into a SAFEARRAY
is done using GetValue()
.