I would like to create a structure to store the data from the database.
I created a function
function result = LoadDataFromDB(query, columnNames)
where column names represents the list of column names, for example {'id', 'year', 'name'...}
After executing the following query
ps=conn.prepareStatement(sql);
rs=ps.executeQuery();
I would like to fill the structure, but haven't figured out how to dynamically access the fields in the structure.
Here is the code piece that should create and fill the structure:
varnamelist = genvarname(columnNames);
result = cell2struct(cell(size(varnamelist(:))), varnamelist(:));
while rs.next()
count=count+1;
for i = 1 : length(columnNames)
fieldname = columnNames(i);
value = char(rs.getString(i));
%result(count).columnNames(i)=char(rs.getString(i));
result(count).(fieldname) = value;
end
end
The main problem is the line
result(count).(fieldname) = value;
To describe a problem below is the copy from the console output:
K>> result(1)
ans =
a: []
b: []
c: []
K>> result(1).('a')
ans =
[]
K>> fieldname
fieldname =
'a'
Concluding from the above output, the command result(1).(fieldname) should access the field 'a' but trying it out, it returns the following error:
K>> result(1).(fieldname)
??? Argument to dynamic structure reference must evaluate to a valid field name.
Does anyone know how to fill the structure dinamically?