Does anyone know how to store a 1-dimensional Matlab array in a single field of a table in Microsoft SQL Server (and how to retrieve it too)? I would like to be able to store an array of Matlab data that isn’t necessarily a fixed size, and I’ve considered storing it as a comma-delimited string, but I am hoping there is a more elegant solution. My thinking is that it should be the same as storing and reading a byte[]. However, I have been trying for hours now and haven’t been able to find anything really helpful on the internet. Here is my Matlab code for storing the array (using ADO):
buf = [1,2,3,4,5];
buf = int8(buf);
cmd = actxserver('ADODB.Command');
cmd.ActiveConnection = db.connection; % db.connection stores my connection
% Note that Matlab throws an error when setting the ActiveConnection. This
% command is still valid though and works, so the error should be ignored
cmd.CommandText = 'INSERT INTO dbo.TESTTABLE VALUES(?)'; % According to the MSDN
% website, this should be @val instead of ?, but for some reason that doesn't
% work and the ? does.
param = cmd.CreateParameter(@val',205,1,8000,buf);
cmd.Parameters.Append(param);
cmd.Execute();
It may be that this code is correct and I just don’t know how to read it back again. Also, I gave an array of size 5 as an example, but I would like to be able to store much larger arrays.
Thanks for your help,
Maddie
For those of you who are attempting a similar problem, I have found a method that works. The code I posted in my question is correct for storing a byte array from Matlab into a MS SQL Server database. You should know, though, that I am storing it into a field of VARBINARY(MAX) and that it automatically gets stored unsigned. Also, it will only store an array that is like
buf = [1,2,3,4,5]
and will only store the first value of and array that is like
buf = [1;2;3;4;5]
When you retrieve it, in a ADO recordset for example, you will have to convert it back to int8 which can be done like in Amro’s answer.
As for the serialization, I wrote a simple Java class that implements Serializable to convert an object to a byte array and vice versa. Since Java can be called from Matlab, this method worked really well, and now I can store and retrieve any Matlab vector, array, or string in a varbinary column.