Code covered by the BSD License  

Highlights from
CSE SQL Database Library

from CSE SQL Database Library by Laurent Cavin
A simple library for dealing with SQL databases.

aout=install;
function aout=install;
% INSTALL   Install script for CSE_SQLDBLib.
%    INSTALL creates the CSE_SQLDBLib folder and the needed
%    entries in the startup.m file.
%    
%    This installation script was generated by using 
%    the MAKEINSTALL tool. For further information
%    visit http://matlab.pucicu.de

% Copyright (c) 2001-2003 by AMRON
% Norbert Marwan, Potsdam University, Germany
% http://www.agnld.uni-potsdam.de
%
% THIS IS A GENERATED INSTALL-FILE, DO NOT EDIT!
% Generation date: 08-Oct-2003 12:56:42
% Last Revision of the template: 2003-06-20
% Version: 3.9.3


install_file='';installfile_info.date='';installfile_info.bytes=[];
time_stamp='';checksum='';checksum_file='';
errcode=0;

try
  warning('off')
  if exist('install.log')==2, delete('install.log'), end
  %rehash
  disp('-----------------------------')
  disp('  INSTALLATION CSE_SQLDBLib');
  disp('-----------------------------')
  install_file=[mfilename,'.m'];
  currentpath=pwd; time_stamp='time_stamp not yet obtained'; checksum='checksum not yet obtained';
  
%%%%%%% read the archive
%%%%%%% and look for checksum and date in archive
  errcode=90;
  disp('  Reading the archiv ')
  fid=fopen(install_file,'r'); 
  fseek(fid,0,'eof'); eofbyte=ftell(fid);
  fseek(fid,16806,'bof');
  while 1
     temp=fgetl(fid);
     startbyte=ftell(fid);
     if length(temp)>1
       if strcmpi(temp,'%<-- Header begins here -->')
          errcode=90.1;
          checksum=fgetl(fid);
          temp1=fgetl(fid);
          temp2=fgetl(fid);
       end
       if strcmpi(temp,'%<-- Header ends here -->')
          startbyte=ftell(fid);
          break
       end
     end
  end
  checksum(1:2)=[];
  fseek(fid,startbyte,'bof');
  errcode=90.2;
  A=fread(fid,eofbyte,'char');
  errcode=90.3;
  checksum_file=dec2hex(sum((1:length(A))'.*A));
  if ~strcmpi(checksum_file,checksum)
    error(['The installation file is corrupt!',10,'Ensure that the archive container were ',...
           'not modified',10,'(check FTP settings, anti-virus scanner for emails etc.)!'])
  else
    disp(['  Checksum test passed (', checksum,')'])
  end
  fclose(fid);

  disp(['  CSE_SQLDBLib version ', temp2(3:end),''])
  time_stamp=temp1(3:end); disp(['  CSE_SQLDBLib time stamp ', time_stamp,'']); 
  
  errcode=91;
  if isunix
      error('CSE:Install', 'Sorry, this library can be used only on PC, as it uses dlls.');
    toolboxpath='noUnixSupport';
  else
    toolboxpath='CSE_SQLDBLib';
  end
  
  
%%%%%%% check for older versions
  
  p=path; i1=0;
  
  while [findstr([lower(toolboxpath),'demo'],lower(p)) findstr(lower(toolboxpath),lower(p)) findstr('',lower(p))]>i1;
    errcode=92;
    i1=[findstr([lower(toolboxpath),'demo'],lower(p)) findstr(lower(toolboxpath),lower(p)) findstr('',lower(p))];
    if ~isempty(i1)
      i1=i1(1);
      if isunix, i2=findstr(':',p); else, i2=findstr(';',p); end
      i3=i2(i2>i1);                 % last index pathname
      if ~isempty(i3), i3=i3(1)-1; else, i3=length(p); end
      i4=i2(i2<i1);                 % first index pathname
      if ~isempty(i4), i4=i4(end)+1; else, i4=1; end
      oldtoolboxpath=p(i4:i3);
      disp(['  Old CSE_SQLDBLib found in ', oldtoolboxpath,''])
      i = input('> Delete old toolbox? Y/N [Y]: ','s');
      if isempty(i), i = 'Y'; end
      if strcmpi('Y',i)
%%%%%%% removing old entries in startup-file
        errcode=94;
        rmpath(oldtoolboxpath)
        if i4>1, p(i4-1:i3)=''; else, p(i4:i3)=''; end
        if exist('startup')
             startupfile=which('startup');
             startuppath=startupfile(1:findstr('startup.m',startupfile)-1);
             if ~isunix
               toolboxroot=fullfile(matlabroot,'toolbox');
             else
               toolboxroot=startuppath;
             end
             instpaths=textread(startupfile,'%[^\n]');
             k=1;
             while k<=length(instpaths)
               if findstr(oldtoolboxpath,instpaths{k})
                 instpaths(k)=[];
               end
               k=k+1;
             end
             fid=fopen(startupfile,'w');
             for i2=1:size(instpaths,1), 
               err=fprintf(fid,'%s\n', char(instpaths{i2})); 
             end
             err=fclose(fid);
        end
%%%%%%% removing old paths
        errcode=93;
        if exist(oldtoolboxpath)==7
           disp(['  Change to ',oldtoolboxpath,''])
           cd(oldtoolboxpath)
           dirnames='';filenames='';
           temp='.:';
           while ~isempty(temp)
             [temp1 temp]=strtok(temp,':');
             if ~isempty(temp1)
               dirnames=[dirnames; {temp1}];
               x2=dir(temp1);
               for i=1:length(x2)
                 if ~x2(i).isdir, filenames=[filenames; {[temp1,'/', x2(i).name]}]; end
         	   if x2(i).isdir & ~strcmp(x2(i).name,'.') & ~strcmp(x2(i).name,'..'), temp=[temp,temp1,filesep,x2(i).name,':']; end
               end
             end
           end
           dirnames=strrep(dirnames,['.',filesep],'');
           for i=1:length(dirnames),l(i)=length(dirnames{i});;end
           [i i4]=sort(l);
           dirnames=dirnames(fliplr(i4));
           for i=1:length(dirnames)
              delete([dirnames{i}, filesep,'*']),
              delete(dirnames{i}),
              disp(['  Removing files in ',char(dirnames{i}),''])
           end
           cd(currentpath)
           delete(oldtoolboxpath)
           disp(['  Removing ',oldtoolboxpath,''])
        end
%%%%%%%
      end
    end
  end
  clear p i i1 i2 i3 i4 temp* x2
  
%%%%%%% add entry into startpath in startup.m
  i=findstr(toolboxpath,path);
  if isempty(i)
     errcode=95;
     disp('  Adding Toolbox into the startup.m file')
     if exist('startup')
        startupfile=which('startup');
        startuppath=startupfile(1:findstr('startup.m',startupfile)-1);
        if ~isunix
           toolboxroot=fullfile(matlabroot,'toolbox');
        else
           toolboxroot=startuppath;
        end
        instpaths=textread(startupfile,'%[^\n]');
  
     else
        if ~isunix
           startupfile=fullfile(matlabroot,'toolbox','local','startup.m');
  	   toolboxroot=fullfile(matlabroot,'toolbox');
  	   instpaths={''};
        else
           cd ~
           if exist('matlab')~=7, mkdir matlab, end
           cd matlab
   	   startuppath=[pwd,'/'];
  	   startupfile=[startuppath,'startup.m'];
  	   toolboxroot=startuppath;
  	   instpaths={''};
        end
     end
     TBfullpath=fullfile(toolboxroot,toolboxpath);
     if ~exist(TBfullpath), err=mkdir(toolboxroot,toolboxpath); end
     instpaths{end+1,1}={['addpath ',TBfullpath]};
     fid=fopen(startupfile,'w');
     for i2=1:size(instpaths,1), err=fprintf(fid,'%s\n', char(instpaths{i2}));end
     err=fclose(fid);
  else
     errcode=96;
     startupfile=which('startup');
     startuppath=startupfile(1:findstr('startup.m',startupfile)-1);
     if ~isunix
        toolboxroot=fullfile(matlabroot,'toolbox');
     else
        toolboxroot=startuppath;
     end
     TBfullpath=fullfile(toolboxroot,toolboxpath);
     if ~exist(TBfullpath), err=mkdir(toolboxroot,toolboxpath); end
  end
  
  
%%%%%%% read the archive
  errcode=97;
  fprintf('  Importing the archiv ')
  cd(currentpath)
  max_sc=30;
  scale=[sprintf('%3.0f',0),'% |',repmat(' ',1,max_sc),'|'];
  fprintf('%s',scale)
  b=''; c.file=''; c.data=''; bfile=''; folder=''; i2=0;
    
    % read ASCII
    errcode=97.1;
    i1=findstr(char(A'),'%<-- ASCII begins here');
    i2=findstr(char(A'),'%<-- ASCII ends here -->');
    
    for k=1:length(i1),
      wb=round(i1(k)*max_sc/eofbyte);
      errcode=97.11;
      scale=[sprintf('%3.0f',100*wb/max_sc),'% |',repmat('*',1,wb),repmat(' ',1,max_sc-wb),'|'];
      fprintf([repmat('\b',1,max_sc+7),'%s'],scale)
      B=A(i1(k):i2(k)-2);
     
      i4=find(B==10);
      i3=[0;i4(1:end-1)]+1;
      filename=strrep(...
                strrep(char(B(i3(1):i4(1)-1)'),'%<-- ASCII begins here: __',''),...
  	      '__ -->','');
      errcode=['97.1',reshape(dec2hex(double(filename))',1,length(filename)*2)];
      i6=findstr(filename,'/');
      if i6>0
         folder=[folder; {filename(1:i6(end)-1)}];
      end
      c(k).file={filename};
      c(k).data=strrep(char(B(i4(1)+3:end)'),[char(10),'%#'],char(10));;
    end
  
    % read binary
    errcode=97.2;
    i1=findstr(char(A'),'%<-- Binary begins here');
    i2=findstr(char(A'),'%<-- Binary ends here -->');
    for k=1:length(i1),
      wb=round(i1(k)*max_sc/eofbyte);
      errcode=97.21;
      scale=[sprintf('%3.0f',100*wb/max_sc),'% |',repmat('*',1,wb),repmat(' ',1,max_sc-wb),'|'];
      fprintf([repmat('\b',1,max_sc+7),'%s'],scale)
      B=A(i1(k):i2(k));
  
      i4=find(B==10);
      i3=[0;i4(1:end-1)]+1;
      i5=findstr(char(B(i3(1):i4(1))'),'__');
      filename=char(B(i5(1)+2:i5(2)-1)');
      errcode=['97.2',reshape(dec2hex(double(filename))',1,length(filename)*2)];
      i6=findstr(filename,'/');
      if i6>0
  	folder=[folder; {filename(1:i6(end)-1)}];
      end
      bfile=[bfile; {filename}];
      nbytes=str2num(char(B(i5(3)+2:i5(4)-1)'));
      temp=reshape(B(i4(1)+1:i4(1)+nbytes),2,nbytes/2);
      b=[b;{temp(2,:)}];
  
    end
    wb=max_sc;
    scale=[sprintf('%3.0f',100*wb/max_sc),'% |',repmat('*',1,wb),repmat(' ',1,max_sc-wb),'|'];
    fprintf([repmat('\b',1,max_sc+7),'%s'],scale)
  fprintf('\n')
  clear temp* i i1 i2 i3 i4 i5 i6 A B
  
  cd(TBfullpath)
  disp(['  Toolbox folder is ',TBfullpath,''])
  
%%%%%%% make sub-directories
  errcode='97.3';
  for i=1:length(folder);
     i1=folder{i}; i2='.'; olddir=pwd;
     if exist([TBfullpath, filesep, i1])~=7
        while ~isempty(i2) & ~isempty(i1)
          cd(i2)
          [i2 i1]=strtok(i1,'/');
          if exist([pwd, filesep, i2])~=7 & exist([pwd, filesep, i2])
             warning(['Found ', i2, ' will be overwritten.'])
             errcode=['97.4',reshape(dec2hex(double(i2))',1,length(i2)*2)];
             delete(i2)
          end
          if ~exist([pwd, filesep, i2])
            disp(['  Make directory ',pwd, filesep, i2,''])
            errcode=['97.5',reshape(dec2hex(double(i2))',1,length(i2)*2)];
            mkdir(i2)
          end
        end
        cd(olddir)
     end
  end

%%%%%%% write the programme files
  errcode=98;
  for i=1:length(c),
    disp(['  Creating ',char(c(i).file),''])
    fid=fopen(char(c(i).file),'w');
    if strcmpi(c(i).file,'info.xml')
       v=version;
       release=str2num(v(findstr(v,'(R')+2:findstr(v,')')-1));
       if release>12, area='toolbox'; icon_path='$toolbox/matlab/icons'; else area='matlab'; icon_path='$toolbox/matlab/general'; end
       i3=findstr(c(i).data,'<matlabrelease>'); i4=findstr(c(i).data,'</matlabrelease>');
       if ~isempty(i3) & i4>i3;
         c(i).data=strrep(c(i).data,c(i).data(i3:i4-1),['<matlabrelease>',num2str(release)]);
       end
       i3=findstr(c(i).data,'<area>'); i4=findstr(c(i).data,'</area>');
       if ~isempty(i3) & i4>i3;
         c(i).data=strrep(c(i).data,c(i).data(i3:i4-1),['<area>',area]);
       end
       c(i).data=strrep(c(i).data,'<icon>$toolbox/matlab/general',['<icon>',icon_path]);
       c(i).data=strrep(c(i).data,'<icon>$toolbox/matlab/icons',['<icon>',icon_path]);
    end
    err=fprintf(fid,'%s',char(c(i).data));
    err=fclose(fid);
  end

%%%%%%% pcode the programme files
  for i=1:length(c),
    try
      [tPath tFile tExt]=fileparts(char(c(i).file));
      if strcmpi(tExt,'.m') & ~strcmpi(tFile,'Readme') & ~strcmpi(tFile,'Contents')
        if mislocked(char(c(i).file)), munlock(char(c(i).file)); clear(char(c(i).file)); end
        disp(['  Pcode ',char(c(i).file),''])
        pcode(char(c(i).file),'-inplace')
      end  
    catch
    end
  end

%%%%%%% write the binary files
  for i=1:length(b),
    disp(['  Creating ',char(bfile(i)),''])
    fid=fopen(char(bfile(i)),'w');
    err=fwrite(fid,b{i}); 
    err=fclose(fid);
  end
  tx=version; i1=findstr(tx,'('); i2=findstr(tx,')'); 
  if str2num(tx(i1+2:i2-1))>=12, rehash, end
  if str2num(tx(i1+2:i2-1))>=13, rehash toolboxcache, end
  clear i i3
  
%%%%%%% removing installation file
  errcode=99;
  cd(currentpath)
  i = input('> Delete installation file? Y/N [Y]: ','s');
  if isempty(i), i = 'Y'; end
  
  if strcmpi('Y',i)
    disp('  Removing installation file')
    delete(install_file)
  end
  
%%%%%%% make toolbox accessible in the current matlab session
  addpath(TBfullpath);
  
  disp('  Installation finished!')
  disp('-----------------------------')
  
  disp('For an overview type:')
  disp(['helpwin ',toolboxpath])
  warning('on')
  
  
%%%%%%% error handling

catch
  z2=whos;x=lasterr;y=lastwarn;
  if ~strcmpi(x,'Interrupt')
    if fid>-1, 
      try, z=ferror(fid); catch, z='No error in the installation I/O process.'; end
    else
      z='File not found.'; 
    end
    installfile_info=dir([currentpath,filesep,install_file]);
    fid=fopen(fullfile(currentpath,'install.log'),'w');
    checksum_test=findstr(x,'The installation file is corrupt!');
    if isempty(checksum_test),checksum_test=0; end
    if ~checksum_test
      err=fprintf(fid,'%s\n','This script is under development and your assistance is');
      err=fprintf(fid,'%s\n','urgently welcome. Please inform the distributor of the');
      err=fprintf(fid,'%s\n','toolbox, where the error occured and send us the following');
      err=fprintf(fid,'%s\n','error report and the informations about the toolbox (distributor,');
      err=fprintf(fid,'%s\n','name etc.). Provide a brief description of what you were');
      err=fprintf(fid,'%s\n','doing when this problem occurred.');
      err=fprintf(fid,'%s\n','E-mail or FAX this information to us at:');
      err=fprintf(fid,'%s\n','    E-mail:  marwan@agnld.uni-potsdam.de');
      err=fprintf(fid,'%s\n','       Fax:  ++49 +331 977 1142');
      err=fprintf(fid,'%s\n\n\n','Thank you for your assistance.');
      err=fprintf(fid,'%s\n',repmat('-',50,1));
      err=fprintf(fid,'%s\n',datestr(now,0));
      err=fprintf(fid,'%s\n',['Matlab ',char(version),' on ',computer]);
      err=fprintf(fid,'%s\n',repmat('-',50,1));
      err=fprintf(fid,'%s\n','Makeinstall Version ==> 3.3.9');
      err=fprintf(fid,'%s\n',['Install File ==> ',install_file,'/',installfile_info.date,'/',num2str(installfile_info.bytes)]);
      err=fprintf(fid,'%s\n',['Container ==> ',time_stamp,'/',checksum]);
      err=fprintf(fid,'%s\n\n',repmat('-',50,1));
      err=fprintf(fid,'%s\n',x);
      err=fprintf(fid,'%s\n',y);
      err=fprintf(fid,'%s\n',z);
      err=fprintf(fid,'%s\n',[' errorcode ==> ',num2str(errcode)]);
      err=fprintf(fid,'%s\n',' workspace dump ==>');
      if ~isempty(z2), 
        err=fprintf(fid,'%s\n',['Name',char(9),'Size',char(9),'Bytes',char(9),'Class']);
        for j=1:length(z2);
          err=fprintf(fid,'%s',[z2(j).name,char(9),num2str(z2(j).size),char(9),num2str(z2(j).bytes),char(9),z2(j).class]);
          if ~strcmp(z2(j).class,'cell') & ~strcmp(z2(j).class,'struct')
            content=eval(z2(j).name);
            content=mat2str(content(1:min([size(content,1),100]),1:min([size(content,2),100])));
            err=fprintf(fid,'\t%s',content(1:min([length(content),500])));
          elseif strcmp(z2(j).class,'struct')
            content=fieldnames(eval(z2(j).name));
            content=char(content); content(:,end+1)=' '; content=content';
            err=fprintf(fid,'\t%s',content(:)');
          end
          err=fprintf(fid,'%s\n','');
        end
      end
    else
      err=fprintf(fid,'%s\n','Installation aborted due to a failed checksum test!');
      err=fprintf(fid,'%s\n',['Checksum should be:     ', checksum]);
      err=fprintf(fid,'%s\n\n',['Checksum of archive is: ', checksum_file]);
      err=fprintf(fid,'%s\n','Ensure that the installation file was not modified by any');
      err=fprintf(fid,'%s\n','other programme, as an anti-virus scanner for emails or a');
      err=fprintf(fid,'%s\n','mis-configured FTP programme.');
    end
    err=fclose(fid);
    disp('----------------------------');
    disp('       ERROR OCCURED ');
    disp('    during installation');
    disp('----------------------------');
    disp(x);
    if ~checksum_test
      disp(z);
      disp(['   errorcode is ',num2str(errcode)]);
      disp('----------------------------');
      disp('   This script is under development and your assistance is ')
      disp('   urgently welcome. Please inform the distributor of the')
      disp('   toolbox, where the error occured and send us the error')
      disp('   report and the informations about the toolbox (distributor,')
      disp('   name etc.). For your convenience, this information has been')
      disp('   recorded in: ')
      disp(['   ',fullfile(currentpath,'install.log')]), disp(' ')
      disp('   Provide a brief description of what you were doing when ')
      disp('   this problem occurred.'), disp(' ')
      disp('   E-mail or FAX this information to us at:')
      disp('       E-mail:  marwan@agnld.uni-potsdam.de')
      disp('          Fax:  ++49 +331 977 1142'), disp(' ')
      disp('   Thank you for your assistance.')
    end
  end
  warning('on')
  cd(currentpath)
end
% -------------------------------------------
% GENERATED ENTRIES - DO NOT MODIFY ANYTHING!
%<-- Header begins here -->
%#4AF47D77A
%#08-Oct-2003 12:56:42
%#1.0 (R1) 
%<-- Header ends here -->
%<-- ASCII begins here: __Contents.m__ -->
%#% CSE SQL Database Library
%#% Version 1.0 (R1) 08-Oct-2003
%#%
%#% General Functions:
%#%   DBInitialize    - Initialize toolbox
%#%   DBOpen          - Open SQL Database
%#%   DBClose         - Release SQL Database
%#%   DBFinish        - Finish all SQL connections
%#%
%#% Table Management:
%#%   DBTableDef      - Get information about a Table
%#%   DBRead          - Read a Table
%#%   DBWrite         - Write a Table
%#%
%#% Query Management:
%#%   DBQuery         - Run an SQL query and obtain resulting table
%#%   DBCreateQuery   - Creates an SQL query table for permanent use
%#%   DBDeleteQuery   - Deletes a previously created permanent query
%#%
%#% SQL Execution:
%#%   DBExecute       - Execute an SQL command
%#%
%#% (c) CSE - L.Cavin, 2003
%#% CSE SQL Database Library uses Access' ActiveX components and therefore
%#% must run on a PC where MS Access is installed.
%#% The library is free to use and distribute as long as the copyrights
%#% notices are kept intact. It is also free to increase and make better;
%#% please send to the author any improvements.
%#%
%#% Contact address: laurent.cavin(a)ethz.ch
%#% Web:             http://ltcmail.ethz.ch/cavin/CSEDBLib.html
%#% Modified at 08-Oct-2003 12:56:42 by MAKEINSTALL
%#
%<-- ASCII ends here -->
%<-- ASCII begins here: __DBClose.m__ -->
%#function DBClose(DB);
%#% DBClose    Release an SQL database
%#%
%#% DBClose(DB);
%#%
%#% Close an SQL database DB.
%#% The variable DB still exists in the caller (and its callers) workspaces.
%#% However, the attached ressources have been released, hence it is not
%#% usable anymore. You should follow this command with a clear DB;
%#%
%#% (c) 2003, CSE; see library header for more information.
%#
%#DB.Close
%#
%#
%<-- ASCII ends here -->
%<-- ASCII begins here: __DBCreateQuery.m__ -->
%#function ErrorCode = DBCreateQuery(DB, QueryName, SQLQuery);
%#% DBCreateQuery   Creates a permanent query (without getting data)
%#%
%#% ErrorCode = DBCreateQuery(DB, QueryName, SQLQuery);
%#%
%#% DB is obtained with DBOpen.
%#% QueryName is a string.
%#% SQLQuery is a SELECT-SQL query, a string.
%#%
%#% ErrorCode is zero for successful completion. After completion, the query
%#% "QueryName" can be used as a normal Table. It is negative if
%#% unsuccessful.
%#%
%#% (c) 2003, CSE; see library header for more information.
%#
%#ErrorCode = 0;
%#
%#if strcmp(SQLQuery(1:6), 'SELECT')
%#	try
%#        DB.CreateQueryDef(QueryName, SQLQuery);
%#	catch
%#        ErrorCode = -1;
%#        blop = lasterr;
%#        warning('CSE:DBLibrary', ['CSE DB Library Error\nUnable to execute query definition:\n%s'], blop);
%#	end
%#else
%#    ErrorCode = -1;
%#    warning('CSE:DBLibrary', ['CSE DB Library Error\nQuery must begin with ''SELECT''. Invalid query:\n%s'], SQLQuery);
%#end
%<-- ASCII ends here -->
%<-- ASCII begins here: __DBDeleteQuery.m__ -->
%#function ErrorCode = DBDeleteQuery(DB, QueryName);
%#% DBDeleteQuery   Deletes a permanent query (without getting data)
%#%
%#% ErrorCode = DBDeleteQuery(DB, QueryName);
%#%
%#% DB is obtained with DBOpen.
%#% QueryName is a string.
%#%
%#% ErrorCode is zero for successful completion. After completion, the query
%#% "QueryName" is destroyed - the underlying data remains of course available.
%#% It is negative if unsuccessful.
%#%
%#% WARNING: This function can also be used to delete tables. Take care, as if
%#% you delete tables, the underlying data will be irremediably destroyed.
%#% No control is done that it is indeed a query you are deleting...
%#%
%#% (c) 2003, CSE; see library header for more information.
%#
%#ErrorCode = 0;
%#
%#try
%#    DB.Execute(['DROP TABLE ' QueryName]);
%#catch
%#    ErrorCode = -1;
%#    blop = lasterr;
%#    warning('CSE:DBLibrary', ['CSE DB Library Error\nUnable to delete query definition:\n%s'], blop);
%#end
%<-- ASCII ends here -->
%<-- ASCII begins here: __DBExecute.m__ -->
%#function ErrorCode = DBExecute(DB, SQLCommand);
%#% DBExecute   Execute an arbitrary SQL command
%#%
%#% ErrorCode = DBExecute(DB, SQLCommand);;
%#%
%#% DB is obtained with DBOpen.
%#% SQLQuery is a any SQL query, a string.
%#%
%#% ErrorCode is zero for successful completion. It is negative if
%#% unsuccessful.
%#%
%#% (c) 2003, CSE; see library header for more information.
%#
%#ErrorCode = 0;
%#
%#try
%#    DB.Execute(SQLCommand);
%#catch
%#    ErrorCode = -1;
%#    blop = lasterr;
%#    warning('CSE:DBLibrary', ['CSE DB Library Error\nUnable to execute SQL command\n"%s":\n%s'], SQLCommand, blop);
%#end
%<-- ASCII ends here -->
%<-- ASCII begins here: __DBFinish.m__ -->
%#% DBFinish  Terminates the use of the SQL database Library
%#%
%#% DBFinish; (no input or output arguments)
%#%
%#% DBFinish will delete all DB Library-related objects.
%#% Of course, only objects present in the caller will be removed; this
%#% function should hence be called in the same function that called
%#% DBInitialize, or from the prompt.
%#%
%#% All objects of the class 'access.application' and children object will be
%#% deleted. If this is not the intended behavior, i.e. if you use other
%#% object of those classes, do not call DBFinish, use clear on each of the
%#% DB Library elements instead.
%#%
%#% (c) 2003, CSE; see library header for more information.
%#
%#temp_var_incl_whos_vars_432325 = whos;
%#for temp_var_incl_whos_vars_299325 = 1:size(temp_var_incl_whos_vars_432325,1)
%#    temp_var_incl_whos_vars_298465 = strfind(temp_var_incl_whos_vars_432325(temp_var_incl_whos_vars_299325).class, 'access.application');
%#    if ~isempty(temp_var_incl_whos_vars_298465)
%#        clear(temp_var_incl_whos_vars_432325(temp_var_incl_whos_vars_299325).name);
%#    end
%#end
%#clear temp_var_incl_whos_vars_298465;
%#clear temp_var_incl_whos_vars_299325;
%#clear temp_var_incl_whos_vars_432325;
%<-- ASCII ends here -->
%<-- ASCII begins here: __DBInitialize.m__ -->
%#function SQLServer = DBInitialize;
%#% DBInitialize  Initialize SQL database Library
%#%
%#% SQLServer = DBInitialize;
%#%
%#% Initialization of database operation; the SQLServer is a handle
%#% to MS Access, that will act as SQL Server.
%#% Pass SQLServer as argument to open a databases.
%#%
%#% DO NOT USE DBInitialize without output argument, the ActiveX link would
%#% be working, but show unpredictable behaviors, for instance an Access
%#% window would keep opening... Therefore, do not use
%#% db = DBOpen(DBInitialize, 'C:\blah\myDB.ips');
%#%
%#% Multiple Servers can be open simultaneously, but one is generally enough,
%#% as many databases can be open at the same time on the same server.
%#%
%#% (c) 2003, CSE; see library header for more information.
%#
%#if isPC
%#    if nargout ~= 1
%#        blop = '';
%#        error('CSE:DBLibrary', 'CSE DB Library Fatal Error\nOne output argument is necessary.%s', blop);
%#	else
%#        try
%#            SQLServer = actxserver('Access.Application');
%#        catch
%#            blop = lasterr;
%#            error('CSE:DBLibrary', ['CSE DB Library Fatal Error\nThis Library is based on MS Access ActiveX engine.\nAccess is not availble on this PC, ' ...
%#                    'hence the library cannot run:\n%s'], blop(28:end));
%#        end
%#    end
%#else
%#    blop = '';
%#    error('CSE:DBLibrary', 'CSE DB Library Fatal Error\nSorry, this library if for PC only - it uses ActiveX functionalties.%s', blop);
%#end
%#
%<-- ASCII ends here -->
%<-- ASCII begins here: __DBOpen.m__ -->
%#function DB = DBOpen(SQLServer, DBName);
%#% DBOpen    Open an SQL database
%#%
%#% DB = DBOpen(SQLServer, DBName);
%#%
%#% Open an SQL database based on the partial or full path DBName.
%#% SQLServer is obtained with DBInitialize.
%#%
%#% DO NOT USE: db = DBOpen(DBInitialize, 'C:\blah\myDB.ips');
%#% An explicit output argument must be used for DBInitialize.
%#%
%#% Multiple databases can be open at the same time on the same server.
%#%
%#% See also DBINITIALIZE and other library functions
%#%
%#% (c) 2003, CSE; see library header for more information.
%#
%#if strcmp(class(SQLServer), 'COM.access.application')
%#    try
%#        DB = SQLServer.DBEngine.OpenDatabase(DBName);
%#    catch
%#        blop = lasterr;
%#        error('CSE:DBLibrary', ['CSE DB Library Error\nUnable to open database:\n%s'], blop);
%#    end
%#else
%#    error('CSE:DBLibrary', 'CSE DB Library Fatal Error\nThe server object passed in argument is not valid.\nIt is of class "%s" instead of "COM.access.application".', class(SQLServer));
%#end
%<-- ASCII ends here -->
%<-- ASCII begins here: __DBQuery.m__ -->
%#function DataTable = DBQuery(DB, SQLQuery, varargin);
%#% DBQuery   Execute a query and get resulting data from an SQL database
%#%
%#% DataTable = DBQuery(DB, SQLQuery);
%#% DataTable = DBQuery(DB, SQLQuery, format);
%#%
%#% SQLQuery is a SELECT-SQL query, a string.
%#% DB is obtained with DBOpen.
%#% format is either 'All' or 'Numeric'. If format is 'All' (default), the
%#% return element DataTable is a cell array. If format is 'Numeric', the
%#% return element is a matrix and non-numeric columns (if any) are dropped.
%#%
%#% (c) 2003, CSE; see library header for more information.
%#
%#if nargin < 3
%#    formatstr = 'All';
%#else
%#    formatstr = varargin{1};
%#end
%#
%#if strcmp(SQLQuery(1:6), 'SELECT')
%#	try
%#        tmp_data = DB.OpenRecordset(SQLQuery);
%#        tmp_DataTable = tmp_data.GetRows(32000)';
%#	catch
%#        tmp_DataTable = [];
%#        blop = lasterr;
%#        warning('CSE:DBLibrary', ['CSE DB Library Error\nUnable to execute and read query:\n%s'], blop);
%#	end
%#	
%#	if strcmpi(formatstr, 'Numeric')
%#        for i = 1:size(tmp_DataTable,1)
%#            for j = 1:size(tmp_DataTable,2)
%#                if isnumeric(tmp_DataTable{i, j})
%#                    DataTable(i, j) = tmp_DataTable{i, j};
%#                end
%#            end
%#        end
%#	else
%#        DataTable = tmp_DataTable;
%#	end
%#else
%#    DataTable = [];
%#    warning('CSE:DBLibrary', ['CSE DB Library Error\nQuery must begin with ''SELECT''. Invalid query:\n%s'], SQLQuery);
%#end
%<-- ASCII ends here -->
%<-- ASCII begins here: __DBRead.m__ -->
%#function DataTable = DBRead(DB, TableName, varargin);
%#% DBRead    Read a Table from an SQL database
%#%
%#% DataTable = DBRead(DB, TableName);
%#% DataTable = DBRead(DB, TableName, format);
%#%
%#% TableName is a string.
%#% DB is obtained with DBOpen.
%#% format is either 'All' or 'Numeric'. If format is 'All' (default), the
%#% return element DataTable is a cell array. If format is 'Numeric', the
%#% return element is a matrix and non-numeric columns (if any) are dropped.
%#%
%#% (c) 2003, CSE; see library header for more information.
%#
%#if nargin < 3
%#    formatstr = 'All';
%#else
%#    formatstr = varargin{1};
%#end
%#
%#try
%#    tmp_data = DB.OpenRecordset(['SELECT * FROM ' TableName ';']);
%#    tmp_DataTable = tmp_data.GetRows(32000)';
%#catch
%#    tmp_DataTable = [];
%#    blop = lasterr;
%#    warning('CSE:DBLibrary', ['CSE DB Library Error\nUnable to read table:\n%s'], blop);
%#end
%#
%#if strcmpi(formatstr, 'Numeric')
%#    for i = 1:size(tmp_DataTable,1)
%#        for j = 1:size(tmp_DataTable,2)
%#            if isnumeric(tmp_DataTable{i, j})
%#                DataTable(i, j) = tmp_DataTable{i, j};
%#            end
%#        end
%#    end
%#else
%#    DataTable = tmp_DataTable;
%#end
%#    
%<-- ASCII ends here -->
%<-- ASCII begins here: __DBTableDef.m__ -->
%#function TableDef = DBTableDef(DB, TableName);
%#% DBTableDef    Analyze Table from an SQL database
%#%
%#% TableDef = DBTableDef(DB, TableName);
%#%
%#% TableName is a string.
%#% DB is obtained with DBOpen.
%#%
%#% TableDef contains the fields
%#%   columns = number of columns
%#%   records = number of records in table
%#%   TypeN(:) = type of the different columns (coded, see below)
%#%   Type(:) = type of the different columns (3 char text, see below)
%#%
%#%     TypeN Type Explanation:
%#%     -----------------------
%#%       0   ???  Unknown
%#%       1   INT  integer
%#%       2   NUM  numeric (float)
%#%       3   TXT  text
%#%       4   LOG  logical
%#%
%#% (c) 2003, CSE; see library header for more information.
%#
%#try
%#    tmp_data = DB.OpenRecordset(['SELECT * FROM ' TableName ';']);
%#    tmp_DataTable = tmp_data.GetRows(1)';
%#catch
%#    tmp_DataTable = [];
%#    blop = lasterr;
%#    warning('CSE:DBLibrary', ['CSE DB Library Error\nUnable to access table:\n%s'], blop);
%#end
%#
%#TableDef.columns = size(tmp_DataTable,2);
%#TableDef.records = size(tmp_DataTable,1);
%#
%#for j = 1:size(tmp_DataTable,2)
%#    if isnumeric(tmp_DataTable{1, j})
%#        if ~isempty(findstr(class(tmp_DataTable{1, j}), 'int'))
%#            TableDef.Type(j,:) = 'INT';
%#            TableDef.TypeN(j) = 1;
%#        else
%#            TableDef.Type(j,:) = 'NUM';
%#            TableDef.TypeN(j) = 2;
%#        end
%#    elseif islogical(tmp_DataTable{1, j})
%#        TableDef.Type(j,:) = 'LOG';
%#        TableDef.TypeN(j) = 4;
%#    elseif ischar(tmp_DataTable{1, j})
%#        TableDef.Type(j,:) = 'TXT';
%#        TableDef.TypeN(j) = 3;
%#    else
%#        TableDef.Type(j,:) = '???';
%#        TableDef.TypeN(j) = 0;
%#    end
%#end
%#    
%<-- ASCII ends here -->
%<-- ASCII begins here: __DBWrite.m__ -->
%#function  errorcode = DBWrite(DB, TableName, DataTable, varargin);
%#% DBWrite    Write a matrix or a cell matrix in a table
%#%
%#% errorcode = DBWrite(DB, TableName, DataTable);
%#% errorcode = DBWrite(DB, TableName, DataTable, option);
%#%
%#% DB is obtained with DBOpen.
%#% TableName is a string.
%#% DataTable must contain the data formated for the table, i.e. ALL columns
%#% of the table must be provided. Usually, it will be a cell array, but it
%#% can be a matrix if the table contains only numerical data.
%#% Option is either 'Append' or 'Replace'. If format is 'Append' (default), the
%#% data is appended to the Table. If format is 'Replace', the table is first
%#% deleted, and the data is then written.
%#% errorcode is zero for successful operation, and negative for errors.
%#%
%#% The behaviors for fields with enforced integrity (usually keys, format
%#% "Auto-Number" in MS Access) is the following:
%#%   If the key field to write is unique, the line is added
%#%   If it is pre-existent, the addition is ignored.
%#%
%#% (c) 2003, CSE; see library header for more information.
%#
%#if nargin < 4
%#    formatstr = 'Append';
%#else
%#    formatstr = varargin{1};
%#end
%#
%#if strcmpi(formatstr, 'Replace')
%#    % delete all table
%#    DB.Execute(['DELETE FROM ' TableName]);
%#end
%#
%#errorcode = 0;
%#
%#for i = 1:size(DataTable,1)
%#    SQLCommand = ['INSERT INTO ' TableName ' VALUES ('];
%#    for j = 1:size(DataTable,2)
%#        if iscell(DataTable)
%#            data = DataTable{i, j};
%#        else
%#            data = DataTable(i, j);
%#        end
%#        if isnumeric(data)
%#            if ~isempty(findstr(class(data), 'int'))
%#                SQLCommand = [SQLCommand int2str(double(data)) ', '];
%#            else
%#                SQLCommand = [SQLCommand num2str(data) ', '];
%#            end
%#        elseif islogical(data)
%#            if data
%#                SQLCommand = [SQLCommand 'TRUE, '];
%#            else
%#                SQLCommand = [SQLCommand 'FALSE, '];
%#            end
%#        else
%#            SQLCommand = [SQLCommand '''' data ''', '];
%#        end
%#    end
%#    SQLCommand = [SQLCommand(1:end-2) ')'];
%#    try
%#        DB.Execute(SQLCommand);
%#    catch
%#        errorcode = -1;
%#        blop = lasterr;
%#        warning('CSE:DBLibrary', ['CSE DB Library Error\nUnable to execute command\n"%s":\n%s'], SQLCommand, blop);
%#	end
%#end
%#
%<-- ASCII ends here -->
%<-- ASCII begins here: __info.xml__ -->
%#<productinfo>
%#
%#<matlabrelease>13</matlabrelease>
%#<name>CSE_DBLibrary</name>
%#<area>toolbox</area>
%#<icon>$toolbox/matlab/icons/matlabicon.gif</icon>
%#
%#<list>
%#
%#<listitem>
%#<label>Start CSE SQL DB Library</label>
%#<callback>DBInitialize.m</callback>
%#<icon>$toolbox/matlab/icons/figureicon.gif</icon>
%#</listitem>
%#
%#<listitem>
%#<label>Help</label>
%#<callback>helpwin CSE_SQLDBLib/</callback>
%#<icon>$toolbox/matlab/icons/bookicon.gif</icon>
%#</listitem>
%#
%#<listitem>
%#<label>Product Page (Web)</label>
%#<callback>web http://ltcmail.ethz.ch/cavin/CSEDBLib.html -browser;</callback>
%#<icon>$toolbox/matlab/icons/webicon.gif</icon>
%#</listitem>
%#
%#</list>
%#
%#</productinfo>
%<-- ASCII ends here -->
%<-- ASCII begins here: __tbclean.m__ -->
%#function tbclean
%#%TBCLEAN   Removes CSE_SQLDBLib.
%#%    TBCLEAN removes all files of CSE_SQLDBLib from
%#%    the filesystem and its entry from the Matlab
%#%    startup file.
%#%    
%#%    This installation script was generated by using 
%#%    the MAKEINSTALL tool. For further information
%#%    visit http://matlab.pucicu.de
%#
%#% Copyright (c) 2002-2003 by AMRON
%#% Norbert Marwan, Potsdam University, Germany
%#% http://www.agnld.uni-potsdam.de
%#%
%#% Generation date: 08-Oct-2003 12:56:42
%#% Last Revision of the template: 2003-01-31
%#% Version: 2.2
%#
%#error(nargchk(0,0,nargin));
%#
%#try
%#  warning('off')
%#  disp('-----------------------------')
%#  disp('    REMOVING CSE_SQLDBLib    ')
%#  disp('-----------------------------')
%#  currentpath=pwd;
%#
%#%%%%%%% check for older versions
%#  
%#  p=path; i1=0;
%#  
%#  while findstr(upper('CSE_SQLDBLib'),upper(p))>i1;
%#    i1=findstr(upper('CSE_SQLDBLib'),upper(p));
%#    if ~isempty(i1)
%#      i1=i1(1);
%#      if isunix, i2=findstr(':',p); else, i2=findstr(';',p); end
%#      i3=i2(i2>i1);                 % last index pathname
%#      if ~isempty(i3), i3=i3(1)-1; else, i3=length(p); end
%#      i4=i2(i2<i1);                 % first index pathname
%#      if ~isempty(i4), i4=i4(end)+1; else, i4=1; end
%#      oldtoolboxpath=p(i4:i3);
%#      disp(['  CSE_SQLDBLib found in ', oldtoolboxpath,''])
%#      i = input('> Delete CSE_SQLDBLib? Y/N [Y]: ','s');
%#      if isempty(i), i = 'Y'; end
%#      if strcmpi('Y',i)
%#%%%%%%% removing old paths
%#        if exist(oldtoolboxpath)==7
%#           disp(['  Removing files in ',oldtoolboxpath,''])
%#           cd(oldtoolboxpath)
%#           dirnames='';filenames='';
%#           temp='.:';
%#           while ~isempty(temp)
%#             [temp1 temp]=strtok(temp,':');
%#             if ~isempty(temp1)
%#               dirnames=[dirnames; {temp1}];
%#               x2=dir(temp1);
%#               for i=1:length(x2)
%#                 if ~x2(i).isdir, filenames=[filenames; {[temp1,'/', x2(i).name]}]; end
%#         	   if x2(i).isdir & ~strcmp(x2(i).name,'.') & ~strcmp(x2(i).name,'..'), temp=[temp,temp1,filesep,x2(i).name,':']; end
%#               end
%#             end
%#           end
%#           dirnames=strrep(dirnames,['.',filesep],'');
%#           for i=1:length(dirnames),l(i)=length(dirnames{i});;end
%#           [i i4]=sort(l);
%#           dirnames=dirnames(fliplr(i4));
%#           for i=1:length(dirnames)
%#              delete([dirnames{i}, filesep,'*'])
%#              delete(dirnames{i})
%#              disp(['  Removing files in ',char(dirnames{i}),''])
%#           end
%#           cd(currentpath)
%#           delete(oldtoolboxpath)
%#           disp(['  Removing folder ',oldtoolboxpath,''])
%#        end
%#%%%%%%% removing entry in startup-file
%#        rmpath(oldtoolboxpath)
%#        if i4>1, p(i4-1:i3)=''; else, p(i4:i3)=''; end
%#          if exist('startup')
%#             disp(['  Removing startup entry'])
%#             startupfile=which('startup');
%#             startuppath=startupfile(1:findstr('startup.m',startupfile)-1);
%#             instpaths=textread(startupfile,'%[^\n]');
%#             k=1;
%#             while k<=length(instpaths)
%#               if ~isempty(findstr(oldtoolboxpath,instpaths{k}))
%#               instpaths(k)=[];
%#               end
%#               k=k+1;
%#             end
%#             fid=fopen(startupfile,'w');
%#             for i2=1:size(instpaths,1), 
%#               err=fprintf(fid,'%s\n', char(instpaths(i2,:))); 
%#             end
%#             err=fclose(fid);
%#             disp(['  CSE_SQLDBLib now removed.'])
%#          end
%#        end
%#    end
%#  end
%#  tx=version; i1=findstr(tx,'('); i2=findstr(tx,')'); if str2num(tx(i1+2:i2-1))>=12, rehash, end
%#  warning on
%#  
%#%%%%%%% error handling
%#
%#catch
%#  x=lasterr;y=lastwarn;
%#  if ~strcmpi(lasterr,'Interrupt')
%#    if fid>-1, 
%#      try, z=ferror(fid); catch, z='No error in the installation I/O process.'; end
%#    else
%#      z='File not found.'; 
%#    end
%#    fid=fopen('deinstall.log','w');
%#    err=fprintf(fid,'%s\n','This script is under development and your assistance is');
%#    err=fprintf(fid,'%s\n','urgently welcome. Please inform the distributor of the');
%#    err=fprintf(fid,'%s\n','toolbox, where the error occured and send us the following');
%#    err=fprintf(fid,'%s\n','error report and the informations about the toolbox (distributor,');
%#    err=fprintf(fid,'%s\n','name etc.). Provide a brief description of what you were');
%#    err=fprintf(fid,'%s\n','doing when this problem occurred.');
%#    err=fprintf(fid,'%s\n','E-mail or FAX this information to us at:');
%#    err=fprintf(fid,'%s\n','    E-mail:  marwan@agnld.uni-potsdam.de');
%#    err=fprintf(fid,'%s\n','       Fax:  ++49 +331 977 1142');
%#    err=fprintf(fid,'%s\n\n\n','Thank you for your assistance.');
%#    err=fprintf(fid,'%s\n',repmat('-',50,1));
%#    err=fprintf(fid,'%s\n',datestr(now,0));
%#    err=fprintf(fid,'%s\n',['Matlab ',char(version),' on ',computer]);
%#    err=fprintf(fid,'%s\n',repmat('-',50,1));
%#    err=fprintf(fid,'%s\n','CSE_SQLDBLib');
%#    err=fprintf(fid,'%s\n',x);
%#    err=fprintf(fid,'%s\n',y);
%#    err=fprintf(fid,'%s\n',z);
%#    err=fclose(fid);
%#    disp('----------------------------');
%#    disp('       ERROR OCCURED ');
%#    disp('   during deinstallation');
%#    disp('----------------------------');
%#    disp(x);
%#    disp(z);
%#    disp('----------------------------');
%#    disp('   This script is under development and your assistance is ')
%#    disp('   urgently welcome. Please inform the distributor of the')
%#    disp('   toolbox, where the error occured and send us the error')
%#    disp('   report and the informations about the toolbox (distributor,')
%#    disp('   name etc.). For your convenience, this information has been')
%#    disp('   recorded in: ')
%#    disp(['   ',fullfile(pwd,'deinstall.log')]), disp(' ')
%#    disp('   Provide a brief description of what you were doing when ')
%#    disp('   this problem occurred.'), disp(' ')
%#    disp('   E-mail or FAX this information to us at:')
%#    disp('       E-mail:  marwan@agnld.uni-potsdam.de')
%#    disp('          Fax:  ++49 +331 977 1142'), disp(' ')
%#    disp('   Thank you for your assistance.')
%#  end
%#  warning('on')
%#  cd(currentpath)
%#end
%#
%<-- ASCII ends here -->

Contact us at files@mathworks.com