MATLAB: Undefined function ‘fetch’ for input arguments of type ‘struct’. when reading and writing to an Access Database

access odbc fetch error dbDatabase Toolbox

Hi all,
This is my first question – please accept my apologies if I format incorrectly.
I call the below code in an infinite loop which runs smoothly for the first ~200 iterations then catches the "Undefined function 'fetch' for input arguments of type 'struct'." error. It is worth noting that in between each iteration I open and close several other tables within the same ODBC connection before reconnecting to this one.
What has me confused is that it runs as it should for the first few hundred iterations. My hunch is that one connection may not close properly but Im not certain.
setdbprefs('DataReturnFormat', 'cellarray');
setdbprefs('NullNumberRead', 'NaN');
setdbprefs('NullStringRead', 'null');
conn = database('ACCESS DB', '', '');
curs = exec(conn, ['SELECT TABLE1.ID_DB'...
' FROM TABLE1 ']);
curs = fetch(curs);
close(curs);
close(conn);
Thanks in advance for any help!

Best Answer

My guess is that you are losing the connection to the database, but I have no idea why. I suggest you do the following. Type
>> dbstop if error
before you try to run that loop. Then execute your code. When the error occurs, the execution will halt, but you will be taken to the editor, at the line where the error occurred. You can see what the variables look like at the time of the error.
My version of your code ran for 500+ iterations, but when I deliberately broke the connection (by disconnecting my VPN), the code halted with the same error you got. The proximate cause of the error is that "curs", instead of being a full cursor object, is instead a structure that is just
curs.Message = 'Invalid connection.'