view m-toolbox/classes/+utils/@jmysql/insert.m @ 43:bc767aaa99a8

CVS Update
author Daniele Nicolodi <nicolodi@science.unitn.it>
date Tue, 06 Dec 2011 11:09:25 +0100
parents f0afece42f48
children
line wrap: on
line source

% INSERT inserts values into a single row of a table using JDBC driver
% specified by the input connection.
%
% Usage: message = insert(conn, table, 'field1', value1, 'field2', value2,...)
%
% M Hewitson
%
% 31-07-07
%
% $Id: insert.m,v 1.4 2009/09/16 13:38:58 hewitson Exp $
%

function message = insert(conn, table, varargin)

  message = '';
  q = sprintf('INSERT INTO %s SET ',  table);
  
  for j=1:2:length(varargin)
    
    col = varargin{j};
    val = varargin{j+1};
    if isnumeric(val)
      if ~any(isnan(val))
        q = [q col '=' num2str(val) ','];
      end
    elseif ischar(val)
      q = [q col '=' '''' val '''' ','];
    else
      error('### val class [%s]', class(val))
    end
        
  end
  
  q = deblank([q(1:end-1) ';']);

  if length(q) > 50
    qdisp = [q(1:50) '...'];
    utils.helper.msg(utils.const.msg.PROC1, 'running query %s', qdisp);
  else
    utils.helper.msg(utils.const.msg.PROC1, 'running query %s', q);
  end
  
  try
    stmt = conn.createStatement;
    stmt.execute(q);
  catch Me
    error('### insert: failed to execute query');
  end
end