Over the past few months, I’ve been working on a project that integrates sophisticated Matlab financial models with a Microsoft environment. Back in February, I wrote about writing from Matlab to Excel using ActiveX. Since then, I’ve been focusing on SQL Server and want to share those experiences.
The simplest way to access a Microsoft SQL Server from Matlab is to use the Database Toolbox. This toolbox allows for an ODBC or a JDBC connection to a database. Since our functions are running in a Microsoft environment, we went with an ODBC connection. The connection is very simple to open:
conn = database('ODBCdatasourcename','ODBCusername','ODBCpassword')
In our case, we would then ‘ping’ the connection to make sure everything has connected properly, and if not, return an error:
try
ping(conn) ;
catch ME
% insert error processing code here …
return;
end
We then execute our SQL and check the results
sql = ‘select a,b from c where d = 10’;
curs = exec(conn, sql) ;
curs = fetch( curs ) ;
NumRows = rows(curs);
if (NumRows < 1 )
% insert error processing code here about no rows returned
return ;
end
result = curs.Data;
for i=1:1:NumRows
if (~isnan(result{i,1}))
a{i} = result{i,1};
b{i} = result{i,2};
end
end
close(curs) ;
close(conn);
It has worked nicely for just about all of our needs. However, for speed and flexibility, we found it useful to use ActiveX for some of our database access.
Recent comments
1 year 20 weeks ago
1 year 22 weeks ago
1 year 26 weeks ago
1 year 45 weeks ago
2 years 3 weeks ago
2 years 13 weeks ago
2 years 14 weeks ago
2 years 17 weeks ago
2 years 17 weeks ago
2 years 21 weeks ago