I understand that you are trying to store sampled data from a Simulink model in a database after every 5 seconds, without having to create a connection every time the samples need to be written to the database table.
To achieve the same, you can make the connection object ‘persistent’ and make checks to the status of the connection object using the ‘isopen’ function. A sample model and code demonstrating the same is given below:
In this model also, the MATLAB function block determines that the timer value gets written to the database table (‘test_table’) only when it is a multiple of 2. The function takes in two inputs, ‘i’ and ‘u’, where ‘i’ acts as the primary key in the table that the function block is writing to, and ‘u’ is the timer value (‘time’ in the database table).
After making the proper connections and storing it in a connection object ‘conn1’, the following check validates that the connection will not be recreated if it is already active.
if isopen(conn1)
if mod(u,2)==0
data = table(i,u, ...
'VariableNames',{'id' 'time' ...
});
sqlwrite(conn1, 'test_table', data);
disp("Writing to table completed...");
end
else
disp('Database connection is not open.');
%then create the connection...
As the simulation is progressed, the desired outcome is achieved as the connection to the database was created only once when there was no connection object and then the values started getting written to the table after every 2 secs.
You can refer to the documentation links for more information on ‘persistent’ and ‘isopen’ by the following commands:
doc persistent
doc isopen
Hope this helps!