Should I just throw in the towel and give up on using MATLAB to talk to a database using .NET?
No, but realize you can also use Java from MATLAB, which is fairly straightforward if you are familiar with JDBC.
I had to write a quick helper function since Class.forName() didn't seem to respect MATLAB's javaclasspath
, and had to convert strings explicitly with char(), but otherwise it worked fine:
// MatlabDBAdapter.java
import java.sql.*;
public class MatlabDBAdapter {
public void loadDriver(String driverClass) throws ClassNotFoundException
{
Class.forName(driverClass);
}
public Connection getConnection(String dburl) throws SQLException
{
return DriverManager.getConnection(dburl);
}
}
example m-file:
% dbexample.m
% adapted from "getting started" section
% of http://www.zentus.com/sqlitejdbc/
% replace the following two lines with
% 1. where you put the compiled MatlabDBAdapter,
% 2. also where you put the driver jar file
javaaddpath('c:/appl/java/project/MatlabDBAdapter/bin');
javaaddpath('c:/appl/java/common/sqlitejdbc-v056.jar');
dba=com.example.test.database.MatlabDBAdapter();
dba.loadDriver('org.sqlite.JDBC');
conn=dba.getConnection('jdbc:sqlite:test.db');
disp ('Adding data....');
stat = conn.createStatement();
stat.executeUpdate('drop table if exists people;');
stat.executeUpdate('create table people (name, occupation);');
prep = conn.prepareStatement(...
'insert into people values (?, ?);');
prep.setString(1, 'Gandhi');
prep.setString(2, 'politics');
prep.addBatch();
prep.setString(1, 'Turing');
prep.setString(2, 'computers');
prep.addBatch();
prep.setString(1, 'Wittgenstein');
prep.setString(2, 'smartypants');
prep.addBatch();
conn.setAutoCommit(false);
prep.executeBatch();
conn.setAutoCommit(true);
disp ('Reading back data....');
rs = stat.executeQuery('select * from people;');
while (rs.next())
% need to explicitly convert java.lang.String using char()
disp(['name = ' char(rs.getString('name'))]);
disp(['job = ' char(rs.getString('occupation'))]);
end
rs.close();
conn.close();