11

This is probably a simple question:

  • How do I connect to Microsoft SQL Server 2008 R2 from Matlab?
  • How do I read a table into a matrix given some SQL query?

Update

I'd prefer a method that doesn't require use of manual setup using ODBC.

Contango
  • 76,540
  • 58
  • 260
  • 305

1 Answers1

26

I present below a review of the different approaches for accessing databases in MATLAB. Here is a list of Stack Overflow questions where some of them were discussed:

Java

MATLAB have an embedded Java JVM, allowing you to directly call the JDBC drivers from MATLAB. You first need to make them available on the Java classpth in MATLAB:

javaclasspath('sqljdbc4.jar');

%# load driver and create connection
driver = com.microsoft.sqlserver.jdbc.SQLServerDriver;
conn  = driver.connect('jdbc:sqlserver://<HOST>:<PORT>;databaseName=<DB>');

%# query database
q = conn.prepareStatement('select * from <TABLE>');
rs = q.executeQuery();
while rs.next()
    char(rs.getString(0))
end
rs.close();
conn.close();

Database Toolbox

If you have access to the Database Toolbox, it can simplify the above as it acts as a wrapper around JDBC/ODBC stuff:

conn = database('<DB>', '<USER>','<PASS>', ...
    'com.microsoft.sqlserver.jdbc.SQLServerDriver', ...
    'jdbc:sqlserver://<HOST>:<PORT>;database=<DB>');
curs = exec(conn, 'select * from <TABLE>');
curs = fetch(curs);
curs.Data
close(curs)
close(conn)

You can also access the database through ODBC. First create a DSN to MSSQL Server (Control Panel > ODBC Data Sources), then use it from the Database Toolbox:

conn = database('myDB', '', '');    %# User/System DSN
%...
close(conn)

COM

You can directly use the ADO OLEDB component from MATLAB. One way is to specify a connection string (DNS-less):

conn = actxserver('ADODB.Connection');
conn.Open('Provider=sqloledb;Data Source=<HOST>;Initial Catalog=<DB>;User Id=<USER>;Password=<PASS>;');
conn.Execute('select * from <TABLE>').GetRows
conn.Close()

.NET

Finally, recent versions of MATLAB added the ability to call .NET from MATLAB. So you can use the ADO.NET data providers:

import System.Data.SqlClient.*
NET.addAssembly('System.Data');
conn = SqlConnection('Data Source=<HOST>;Initial Catalog=<DB>');
conn.Open();
q = SqlCommand('select * from <TABLE>', conn);
r = q.ExecuteReader();
while r.Read()
    char(r.GetString(0))
end
r.Close()
conn.Close()
Community
  • 1
  • 1
Amro
  • 123,847
  • 25
  • 243
  • 454
  • Great summary. I think it is worth adding (from one of those links you posted) direct mention of this toolbox: http://www.mathworks.com/matlabcentral/fileexchange/29615-adodbtools it is very simple and fast. Outputs queries as cell tables or struct arrays! – Dan Jul 17 '12 at 11:36
  • @Dan: Yes I've come across this toolbox before, definitely useful. Underneath, it uses the same methods shown in the COM approach above (unfortunately just like .NET, COM/ActiveX approach is a Windows-only solution and less portable) – Amro Jul 17 '12 at 18:30
  • Do any of these methods let you get bit-exact copies of database contents into Matlab? Or do you have to read numerics or binary blobs (for example) as character strings and reconstruct them as Matlab types (which will be terrifically slow)? – Ahmed Fasih Oct 24 '13 at 14:57
  • @Ahmed, did you ever found an answer to your question ? We now hitting this issue that we have bigint in sql server and get it back as strings. Which is nonsense in terms of performance. – nojetlag Mar 13 '14 at 09:13
  • @nojetlag no, I was asking this question as part of tool risk evaluation, thankfully not because I needed an answer. Good luck. – Ahmed Fasih Mar 14 '14 at 09:07
  • In case anyone else struggles as I did, you need to ensure that when you're using the Java approach described above, the sqljdbc*.jar file you use will run in the version of Java that your Matlab is using. Initially, I tried to use the sqljdbc41.jar (requires Java 1.7/JRE 7), but my Matlab (R2012a) uses Java 1.6. The class won't load, but silently fails. – Michael Repucci Jul 31 '15 at 18:36
  • what is about [JSONlab: a toolbox to encode/decode JSON/UBJSON files in MATLAB/Octave](http://iso2mesh.sourceforge.net/cgi-bin/index.cgi?jsonlab)? – Stefan Apr 10 '18 at 12:33