diff m-toolbox/classes/+utils/@mysql/connect.m @ 2:18e956c96a1b database-connection-manager

Add LTPDADatabaseConnectionManager implementation. Matlab code
author Daniele Nicolodi <nicolodi@science.unitn.it>
date Sun, 04 Dec 2011 21:23:09 +0100
parents
children 977eb37f31cb
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/m-toolbox/classes/+utils/@mysql/connect.m	Sun Dec 04 21:23:09 2011 +0100
@@ -0,0 +1,38 @@
+function conn = connect(hostname, database, username, password)
+% CONNECT Opens a connection to the given database.
+%
+% CALL:
+%
+%   conn = utils.mysql.connect(hostname, database, username, password)
+%
+% This function returns a Java object implementing the java.sql.Connection
+% interface connected to the given database using the provided credentials.
+% If the connection fails because the given username and password pair is not
+% accepted by the server an utils:mysql:connect:AccessDenied error is thrown.
+%
+
+  % informative message
+  import utils.const.*
+  utils.helper.msg(msg.PROC1, 'connection to mysql://%s/%s username=%s', hostname, database, username);
+
+  % connection credential
+  uri = sprintf('jdbc:mysql://%s/%s', hostname, database);
+  db = javaObject('com.mysql.jdbc.Driver');
+  pl = javaObject('java.util.Properties');
+  pl.setProperty(db.USER_PROPERTY_KEY, username);
+  pl.setProperty(db.PASSWORD_PROPERTY_KEY, password);
+
+  try
+    % connect
+    conn = db.connect(uri, pl);
+  catch ex
+    % haven't decided yet if this code should be here or higher in the stack
+    if strcmp(ex.identifier, 'MATLAB:Java:GenericException')
+      % exceptions handling in matlab sucks
+      if ~isempty(strfind(ex.message, 'java.sql.SQLException: Access denied'))
+        throw(MException('utils:mysql:connect:AccessDenied', '### access denied').addCause(ex));
+      end
+    end
+    rethrow(ex);
+  end
+end