Tag Archives: java

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)
  • 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

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