% 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

