Home >Database >Mysql Tutorial >MATLAB中关于MySQL数据库的操作_MySQL

MATLAB中关于MySQL数据库的操作_MySQL

WBOY
WBOYOriginal
2016-06-01 13:14:541306browse

首先要安装mysql驱动程序包,详细步骤如下:

Step 1:将mysql-connector-java-5.1.7-bin.jar文件拷贝到....../MATLAB/R2009a/java/jar/toolbox

Step 2:到....../MATLAB/R2009a/toolbox/local目录下,找到classpath.txt文件,打开,并添加用来加载mysql的jdbc驱动语句:

$matlabroot/java/jar/toolbox/mysql-connector-java-5.1.7-bin.jar

Step 3:重新打开MATLAB即可

驱动程序安装成功后,接来下要是matlab连接mysql数据库的代码:

conn=database('databasename','username','password','driver','databaseurl')

连接成功后,返回连接对象。

参数如下:

*databasename: 数据库名称.

*driver: JDBC driver.

*username and password: 用户名和密码.

*databaseurl: 类似于jdbc:subprotocol:subname. subprotocol是数据库类型,

subname类似于//hostname:port/databasename.

如果matlab和数据库建立了连接,将返回类似于如下信息:

Instance: 'SampleDB'

UserName: ''Driver: []URL: []

Constructor: [1x1com.mathworks.toolbox.database.databaseConnect]

Message: []

Handle: [1x1 sun.jdbc.odbc.JdbcOdbcConnection]

TimeOut: 0

AutoCommit: 'off'

Type: 'Database Object'

连接mysql的代码如下:

conn = database('tissueppi','root','root','com.mysql.jdbc.Driver','jdbc:mysql://localhost:3306/tissueppi');

连接成功后,就可以用exec函数执行sql语句

exec函数执行sql语句并返回一个开指针

语法如下:

curs =exec(conn,'sqlquery')

例如:curs = exec(conn, 'select * fromcustomers')

执行完查询后,还要将查询结果从开放cursor对象导入到对象curs中,该功能是用

cursor.fetch函数实现的。
语法如下:

curs =fetch(curs)

使用curs.Data来显示数据,curs.Data返回一个CELL结构,可以先把CELL结构转换成

MATRIX结构再取值:

cur=cell2mat(cur)

a=cur(1,1);

则查询结果就加到了向量a中

注意:

在exec函数执行查询过程中,有的sql语句要输入变量,这时可使用strcat函数完成该

功能。

t =strcat(s1, s2, s3, ...)

for(t=1:10)

sql1 = strcat('select count(did) from rss_genepairs_u wheregocc>=',num2str(t),' || gomf>= ',num2str(t),' || gobp >=',num2str(t));

end
完整代码如下:

conn =database('tissueppi','root','root','com.mysql.jdbc.Driver','jdbc:mysql://localhost:3306/tissueppi');

for t=0.5:0.01:0.91

for x=0.5:0.1:11

sql = strcat('select count(did) from rss_genepairs_x2 where score=',num2str(t),' || gomf>= ',num2str(t),' || gobp >=',num2str(t),')');

aTemp = exec(conn,sql);

aTemp = fetch(aTemp);

a = aTemp.Data;

a = cell2mat(a);

a= a(1,1);endend
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn