本文分两部分,1、通过sql语句操作数据库。2、通过ddl操作数据库
一 通过ODBC实现到oracle的连接
1)控制面板->管理工具->ODBC数据源->在系统DSN中添加oracle数据源;
2)matlab命令行中输入建立连接的命令:
conn_odbc = database(‘QUIK‘, ... %ODBC名称 ‘QUIK‘, ... %登录用户名 ‘QUIK‘) %登录密码
二 通过JDBC建立与oracle的连接,此处我使用的也是利用JDBC操作。
1)找到jdbc的驱动程序文件D:\oracle_app\lcm\product\11.2.0\dbhome_1\jdbc\lib\ojdbc6.jar,将其复制到
matlab安装目录的java子目录D:\Program Files\MATLAB\R2013a\java\jar\toolbox;
2)修改matlab的classpath文件:D:\Program Files\MATLAB\R2013a\toolbox\local\classpath.txt,在结尾添加一
行内容:
$matlabroot/java/jar/toolbox/ojdbc6.jar
3)matlab命令行中输入建立连接的命令:
conn_jdbc = database(‘QUIK‘, ... %数据库服务名 ‘QUIK‘, ... %登录用户名 ‘QUIK‘, ... %登录密码 ‘oracle.jdbc.driver.OracleDriver‘, ... %驱动名称 ‘jdbc:oracle:thin:@localhost:1521:‘) %连接字符串
通过ping命令查看连接状况:
ping(conn_odbc) ping(conn_jdbc)
1、数据库实际查询操作
%% Read data from Oracle % Create a connection from Matlab to Oracle % Oracle DataBase Connection Usage % conn = database(‘DBname‘,‘UserName‘,‘UserPwd‘,‘oracle.jdbc.driver.OracleDriver‘,‘jdbc:oracle:thin:@localhost:1521:‘); % conn = database(‘AVM‘,‘m‘,‘m‘, ‘oracle.jdbc.driver.OracleDriver‘,‘jdbc:oracle:thin:@10.84.13.18:1521:‘); % Execute query and get data from Oracle curs = exec(conn, ‘select * from mes_imp_operate_log d‘); data = fetch(curs); % Get number from Oracle data = data.Data; % Last Close Cursor close(curs); close(conn); data
结果输出(和实际中一样的结果,结果存储类似矩阵):
2、我们执行一条Insert的ddl试试:
%% Read data from Oracle % Create a connection from Matlab to Oracle % Oracle DataBase Connection Usage % conn = database(‘DBname‘,‘UserName‘,‘UserPwd‘,‘oracle.jdbc.driver.OracleDriver‘,‘jdbc:oracle:thin:@localhost:1521:‘); % 服务名记住要是Oracle实际中的,可能不是tns配置的 conn = database(‘A‘,‘mssd‘,‘mis‘, ‘oracle.jdbc.driver.OracleDriver‘,‘jdbc:oracle:thin:@10.80.10.13:1521:‘); % Execute query and get data from Oracle sql = ‘INSERT INTO mes_imp_operate_log(id, create_time, user_id, operate_type, remark, trace_no)VALUES(mes_imp_operate_log_s.nextval, SYSDATE, 3, ‘‘ss‘‘, ‘‘录入test‘‘, ‘‘test‘‘ )‘; curs1 = exec(conn, sql); % Commit Or roolback Transction %exec(conn_odbc, ‘rollback‘); exec(conn, ‘commit‘); curs = exec(conn, ‘SELECT * FROM mes_imp_operate_log‘); data = fetch(curs); % Get number from Oracle data = data.Data; % Last Close Cursor close(curs); close(conn);
Java程序调用matlab
,将.m 文件打包成jar,Eclipse调用,可以参考: