1

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?

Niko Gamulin
  • 66,025
  • 95
  • 221
  • 286

1 Answers1

1

Yes, there's dynamic field reference. You can find more on it here for example.

Dynamic reference can be used to assign or reference fields in structures like so:

fieldName = 'some_field';
your_struct.(fieldName) = fieldValue

So, in your case, that would mean modifying the inner loop body to

fieldname = columnNames{i};
value = rs.getString{i};
result(count).(fieldname) = value;
Rody Oldenhuis
  • 37,726
  • 7
  • 50
  • 96
  • Yes, this is what I'm looking for, but don't know what causes the error. I modified the code above so it might be more cleare where the main problem is. – Niko Gamulin Aug 31 '12 at 12:03
  • 1
    @NikoGamulin Try `fieldname = columnNames{i};`, i.e., are you sure that it's a regular string array, or is it a cell-array? – Rody Oldenhuis Aug 31 '12 at 12:06
  • @NikoGamulin I think using `value = rs.getString{i};` instead of casting to char will be faster; give it a try. – Rody Oldenhuis Aug 31 '12 at 12:15