Friday, June 3, 2011

Connect to SQL Server from Matlab

Alternatively you can create and use an ODBC connection, but if you would rather not do that for every database and server you wish to connect to, you can do the following using the JDBC driver.

1. Download the JDBC driver from Microsoft from:

2. Execute it, and it will be decompressed to the selected location

3. Create folder c:/SQLJDBC and place sqljdbc_2.0 inside it.

4. Start the Notepad application as administrator and open the file:

C:\Program Files\MATLAB\R2010a\toolbox\local\classpath.txt

5. Add a reference like this to the JDBC driver after the last line of that file:


6. After that you have to restart MATLAB and then you can test the connection:

dbConn = database('master', 'user', 'password', '', 'jdbc:sqlserver://localhost:1433;databaseName=master;');

7. To test the connection you can execute:


8. Please note that the local instance of SQL Server requires you to have the TCP/IP protocol network connections enabled.


Other references:

1 comment:

  1. John,

    Thanks for posting this. It got me most of the way through the process. The only thing I would add is that if you get an error message about not being able to establish a connection (or alternatively, an error message about not being able to close the connection) download and run sysinternals to see what port SQL Server is using. It might not be using the default port. It might be using another port altogether.

    Thanks again!