Connect and access MySQL database

Connecting to MySQL database from Matlab is not that hard (as I thought before). Matlab apparently use JDBC to connect to database server.
So, here’s simple steps to connect to MySQL server:

  • Open the zip/tar.gz file and extract only the .jar file on your Matlab project directory.
mysql connector/j archive

Only extract that .jar file

  • Now you are ready to use your MySQL driver inside Matlab.
  • Open Matlab and set your “Current Folder” to where you extract that MySQL Connector/J driver.
matlab current folder

matlab current folder

 

  • For this tutorial, I’ll use cdcols database from XAMPP sample MySQL database. (database name=cdcols, mysql username=root and mysql password is empty).
  • Load MySQL driver (as I’m writing this, the current driver version is: 5.1.21)
javaaddpath 'mysql-connector-java-5.1.21-bin.jar';
  • Connecting to database
conn=database('cdcol', 'root', '', 'com.mysql.jdbc.Driver', 'jdbc:mysql://localhost/');
  • We will access cds table, here’s the table structure (taken from open sourced HeidiSQL)
cds table structure

cds table structure

  • SELECT Query on cds table
e = exec(conn,'SELECT * FROM cds');
  • fetch 2 rows from the resultset/recordset. The return value would be a cell of matrices
dat=fetch(e, 2);
  • accessing the record value
% second row, first column ('titel' field)
dat.Data{2,1}
  • INSERT query on cds table (you can use the same technique on UPDATE and DELETE query)
r=exec(conn, 'insert into cds(`titel`, `interpret`, `jahr`) values(''Kisah 2002 Malam'', ''Peterpan'', 2002)');
  • table cds after above INSERT query (screenshot also from HeidiSQL):
cds table after insert

data after INSERT query

  • Closing database connection
close(conn);

That’s it. It’s not that hard isn’t it?

  1. Thank you very much. It was very helpful

  2. I have downloaded the file, but from where i extract the jar file? please help, this is all new to me.

  3. John Richards

    Does Database package need to be installed for this? i cannot get the database statement to work.

  4. thanks a
    lot it’s working

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>