从 MATLAB 调用 ADO.NET

发布于 2024-08-25 15:22:02 字数 706 浏览 1 评论 0原文

可以从 MATLAB 调用 .NET,因此我想尝试使用 ADO.NET 连接到数据库。

我似乎遇到了阻塞问题 - 每当您尝试创建 Command 对象时,它都会抛出错误。

你可以自己尝试一下:

>> NET.addAssembly('System.Data');
>> sqlconn = System.Data.SqlClient.SqlConnection();
>> sqlconn.State

ans = 

    Closed    

>> % So far, so good
>> sqlcmd = System.Data.SqlClient.SqlCommand();
??? Error using ==> System.Data.SqlClient.SqlCommand
'Connection' is already defined as a property.

>> 

有人对此有一些见解吗?对于 MATLAB 来说,这似乎是一个纯粹且简单的错误 - 也许每个恰好具有名为“Connection”的属性的 .NET 类都会发生这种情况。

我是否应该认输并放弃使用 MATLAB 来使用 .NET 与数据库通信?


答案(感谢 Fazil 的调查):将 MATLAB 升级到 2009a 以上的版本

It's possible to call .NET from MATLAB, so I thought I would try to use ADO.NET to connect to a database.

I seem to have hit a blocking problem - anytime you try and create a Command object, it throws an error.

You can try this yourself:

>> NET.addAssembly('System.Data');
>> sqlconn = System.Data.SqlClient.SqlConnection();
>> sqlconn.State

ans = 

    Closed    

>> % So far, so good
>> sqlcmd = System.Data.SqlClient.SqlCommand();
??? Error using ==> System.Data.SqlClient.SqlCommand
'Connection' is already defined as a property.

>> 

Does anyone have some insight into this? It seems like a pure and simple bug on MATLAB's part - maybe it happens with every .NET class that happens to have a property called "Connection".

Should I just throw in the towel and give up on using MATLAB to talk to a database using .NET?


Answer (thank's to Fazil's investigations): Upgrade MATLAB to a version greater than 2009a.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

旧城空念 2024-09-01 15:22:02
NET.addAssembly('System.Data');
sqlconn = System.Data.SqlClient.SqlConnection();
sqlcmd = sqlconn.CreateCommand();
sqlcmd.CommandText = "SELECT count(id) FROM sometable";
sqlconn.Open();
sqlrdr = sqlcmd.ExecuteReader();
sqlrdr.Read();
sqlrdr.GetInt64(0)
NET.addAssembly('System.Data');
sqlconn = System.Data.SqlClient.SqlConnection();
sqlcmd = sqlconn.CreateCommand();
sqlcmd.CommandText = "SELECT count(id) FROM sometable";
sqlconn.Open();
sqlrdr = sqlcmd.ExecuteReader();
sqlrdr.Read();
sqlrdr.GetInt64(0)
川水往事 2024-09-01 15:22:02

我是否应该认输并放弃使用 MATLAB 来使用 .NET 与数据库通信?

不,但要意识到您还可以从 MATLAB 使用 Java,如果您熟悉 JDBC,这将相当简单。

我必须编写一个快速帮助函数,因为 Class.forName() 似乎不尊重 MATLAB 的 javaclasspath,并且必须使用 char() 显式转换字符串,但除此之外它工作得很好:

// 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);
    }
}

示例 m-文件:

% 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();

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();
温折酒 2024-09-01 15:22:02

我无法在 MATLAB 中重现该问题。您使用的是哪个版本的 MATLAB?

>> version

ans =

7.9.1.705 (R2009b) Service Pack 1

>> NET.addAssembly('System.Data');
sqlconn = System.Data.SqlClient.SqlConnection();
sqlconn.State
sqlcmd = System.Data.SqlClient.SqlCommand()

ans = 

    Closed    


sqlcmd = 

  System.Data.SqlClient.SqlCommand handle
  Package: System.Data.SqlClient

  Properties:
                Connection: []
    NotificationAutoEnlist: 1
              Notification: []
               Transaction: []
               CommandText: [1x1 System.String]
            CommandTimeout: 30
               CommandType: [1x1 System.Data.CommandType]
         DesignTimeVisible: 1
                Parameters: [1x1 System.Data.SqlClient.SqlParameterCollection]
          UpdatedRowSource: [1x1 System.Data.UpdateRowSource]
                      Site: []
                 Container: []

  Methods, Events, Superclasses

>> 

I'm not able to reproduce the issue in MATLAB. Which version of MATLAB are you using?

>> version

ans =

7.9.1.705 (R2009b) Service Pack 1

>> NET.addAssembly('System.Data');
sqlconn = System.Data.SqlClient.SqlConnection();
sqlconn.State
sqlcmd = System.Data.SqlClient.SqlCommand()

ans = 

    Closed    


sqlcmd = 

  System.Data.SqlClient.SqlCommand handle
  Package: System.Data.SqlClient

  Properties:
                Connection: []
    NotificationAutoEnlist: 1
              Notification: []
               Transaction: []
               CommandText: [1x1 System.String]
            CommandTimeout: 30
               CommandType: [1x1 System.Data.CommandType]
         DesignTimeVisible: 1
                Parameters: [1x1 System.Data.SqlClient.SqlParameterCollection]
          UpdatedRowSource: [1x1 System.Data.UpdateRowSource]
                      Site: []
                 Container: []

  Methods, Events, Superclasses

>> 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文