Matlab连接MySQL数据库入门

时间:2021-10-09 03:35:48

1、加载MySQL的jdbc驱动

(1)将mysql-connector-java-5.1.28-bin.jar拷贝到D:\Program Files\MATLAB\R2014a\java\jar\toolbox目录;

Matlab连接MySQL数据库入门

(2)打开D:\Program Files\MATLAB\R2014a\toolbox\local目录classpath.txt文件,添加用来加载MySQL的jdbc驱动语句,语句如下:

$matlabroot/java/jar/toolbox/mysql-connector-java-5.1.28-bin.jar
Matlab连接MySQL数据库入门

Matlab连接MySQL数据库入门

2、重启Matlab

3、获取连接对象

>> conn = database('hwd', 'root', '123456', 'com.mysql.jdbc.Driver', 'jdbc:mysql://localhost:3306/hwd')

conn =

Instance: 'hwd'
UserName: 'root'
Driver: 'com.mysql.jdbc.Driver'
URL: 'jdbc:mysql://localhost:3306/hwd'
Constructor: [1x1 com.mathworks.toolbox.database.databaseConnect]
Message: []
Handle: [1x1 com.mysql.jdbc.JDBC4Connection]
TimeOut: 0
AutoCommit: 'on'
Type: 'Database Object'

>>

4、执行SQL语言

(1)查询user表

>> curs = exec(conn, 'select * from user')

curs =

Attributes: []
Data: 0
DatabaseObject: [1x1 database]
RowLimit: 0
SQLQuery: 'select * from user'
Message: []
Type: 'Database Cursor Object'
ResultSet: [1x1 com.mysql.jdbc.JDBC4ResultSet]
Cursor: [1x1 com.mathworks.toolbox.database.sqlExec]
Statement: [1x1 com.mysql.jdbc.StatementImpl]
Fetch: 0

>>
>> curs = fetch(curs) curs =         Attributes: []              Data: {2x3 cell}    DatabaseObject: [1x1 database]          RowLimit: 0          SQLQuery: 'select * from user'           Message: []              Type: 'Database Cursor Object'         ResultSet: [1x1 com.mysql.jdbc.JDBC4ResultSet]            Cursor: [1x1 com.mathworks.toolbox.database.sqlExec]         Statement: [1x1 com.mysql.jdbc.StatementImpl]             Fetch: [1x1 com.mathworks.toolbox.database.fetchTheData]>> 

(2)返回CELL

>> cur = curs.Data

cur =

[1] 'tom' '123'
[2] 'jerry' '456'

>>

(3)取值

>> id = cur(1,1)

id =

[1]

>>