WICHTIG: Der Betrieb von goMatlab.de wird privat finanziert fortgesetzt. - Mehr Infos...

Mein MATLAB Forum - goMatlab.de

Mein MATLAB Forum

 
Gast > Registrieren       Autologin?   

Partner:




Forum
      Option
[Erweitert]
  • Diese Seite per Mail weiterempfehlen
     


Gehe zu:  
Neues Thema eröffnen Neue Antwort erstellen

Java exception verursacht durch fastinsert.m

 

Lloyd Blankfein
Forum-Century

Forum-Century



Beiträge: 149
Anmeldedatum: 23.02.11
Wohnort: ---
Version: ---
     Beitrag Verfasst am: 01.11.2011, 18:13     Titel: Java exception verursacht durch fastinsert.m
  Antworten mit Zitat      
Hallo,

ich benutze das file fastinsert.m aus der database tollbox.
Hierbei tritt dieser Fehler auf:

??? Error using ==> ParamDAO.ParamDAO>ParamDAO.setParam at 154
Java exception occurred:
sun.jdbc.odbc.JdbcOdbcBatchUpdateException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in
INSERT INTO statement.

at sun.jdbc.odbc.JdbcOdbcPreparedStatement.emulateExecuteBatch(Unknown Source)

at sun.jdbc.odbc.JdbcOdbcPreparedStatement.executeBatchUpdate(Unknown Source)

at sun.jdbc.odbc.JdbcOdbcStatement.executeBatch(Unknown Source)


Error in ==> WOverview>pb_details_ov_Callback at 110
ParamDAO.setParam(selectedParameter.Parameter_ID);

Error in ==> gui_mainfcn at 96
feval(varargin{:});

Error in ==> WOverview at 16
gui_mainfcn(gui_State, varargin{:});

Error in ==> @(hObject,eventdata)WOverview('pb_details_ov_Callback',hObject,eventdata,guidata(hObject))


??? Error using ==> waitfor
Error while evaluating uicontrol Callback

Code:

function fastinsert(connect,tableName,fieldNames,data)
%FASTINSERT Export MATLAB cell array data into database table.
%   FASTINSERT(CONNECT,TABLENAME,FIELDNAMES,DATA).
%   CONNECT is a database connection handle structure, FIELDNAMES
%   is a string array of database column names, TABLENAME is the
%   database table, DATA is a MATLAB cell array.
%
%
%   Example:
%
%
%   The following FASTINSERT command inserts the contents of
%   the cell array in to the database table yearlySales
%   for the columns defined in the cell array colNames.
%
%
%   fastinsert(conn,'yearlySales',colNames,monthlyTotals);
%
%   where
%
%   The cell array colNames contains the value:
%
%   colNames = {'salesTotal'};
%
%   monthlyTotals is a cell array containing the data to be
%   inserted into the database table yearlySales
%  
%   fastinsert(conn,'yearlySales',colNames,monthlyTotals);
%
%
%   See also INSERT, UPDATE, MSSQLSERVERBULKINSERT, MYSQLBULKINSERT, ORACLEBULKINSERT.  

%   Copyright 1984-2005 The MathWorks, Inc.
%   $Revision: 1.1.6.18 $   $Date: 2009/12/22 18:51:21 $%

error(nargchk(4,4,nargin));

% Check for valid connection

if isa(connect.Handle,'double')
   
    error('database:fastinsert:invalidConnection','Invalid connection.')
   
end

% Create start of the SQL insert statement
% First get number of columns in the cell array

%Get dimensions of data
switch class(data)
   
  case {'cell','double'}
    [numberOfRows,cols] = size(data);   %data dimensions
   
  case 'struct'
    sflds = fieldnames(data);
    fchk = setxor(sflds,fieldNames);
    if ~isempty(fchk)
      error('database:fastinsert:fieldMismatch','Structure fields and insert fields do not match.')
    end
    numberOfRows = size(data.(sflds{1}),1);
    cols = length(sflds);
   
    %Get class type of each field to be used later
    numberOfFields = length(sflds);
    fieldTypes = cell(numberOfFields,1);
    for i = 1:numberOfFields
      fieldTypes{i} = class(data.(sflds{i}));
    end

  case 'dataset'
    dSummary = summary(data);
    sflds = {dSummary.Variables.Name};
    fchk = setxor(sflds,fieldNames);
    if ~isempty(fchk)
      error('database:database:writeMismatch','Dataset variable names and insert fields do not match.')
    end
    numberOfRows = size(data.(sflds{1}),1);
    cols = length(sflds);
   
    %Get class type of each field to be used later
    numberOfFields = cols;
    fieldTypes = cell(numberOfFields,1);
    for i = 1:numberOfFields
      fieldTypes{i} = class(data.(sflds{i}));
    end
   
  otherwise
    error('database:fastinsert:inputDataError','Input data must be a cell array, matrix, or structure')
   
end

% Case 1 all fields are being written to in the target database table.
insertField = '';
tmpq = '';

% Create the field name string for the INSERT statement .. this defines the
% fields in the database table that will be receive data.
% Also build variable ?'s string for later set* commands

for i=1:cols,
  if ( i == cols),
    insertField = [ insertField fieldNames{i}];  %#ok
    tmpq = [tmpq '?)'];                          %#ok
  else
    insertField = [ insertField fieldNames{i} ',' ]; %#ok
    tmpq = [tmpq '?,'];                              %#ok
  end  
end

% Create the head of the SQL statement
startOfString = [ 'INSERT INTO '  tableName ' (' insertField ') ' 'VALUES ( ' ];

% Get NULL string and number preferences
prefs = setdbprefs({'NullStringWrite','NullNumberWrite'});
nsw = prefs.NullStringWrite;
nnw = str2num(prefs.NullNumberWrite);    %#ok

%Create prepared statement object
tmpConn = connect.Handle;
StatementObject = tmpConn.prepareStatement([startOfString tmpq]);

%Get Database name
dMetaData = dmd(connect);
sDbName = get(dMetaData,'DatabaseProductName');

%Determine type values by fetching one row of data from table
switch sDbName  %Query only a single row where possible for speed
     
  case {'MySQL'}
    e = exec(connect,['select ' insertField ' from ' tableName ' LIMIT 0']);
  case {'Microsoft SQL Server','ACCESS'}
    e = exec(connect,['select TOP 1 ' insertField ' from ' tableName]);
  case {'Oracle'}
    e = exec(connect,['select ' insertField ' from ' tableName ' where ROWNUM <= 1']);  
  otherwise
    e = exec(connect,['select ' insertField ' from ' tableName]);    
end
if ~isempty(e.Message)
  error('database:database:insertError',e.Message)
end
e = fetch(e,1);
if ~isempty(e.Message)
  error('database:database:insertError',e.Message)
end
a = attr(e);
close(e)

for i = 1:numberOfRows,  
 
    for j = 1:cols
     
      switch class(data)
       
        case 'cell'

          tmp = data{i,j};
         
        case 'double'
           
          tmp = data(i,j);    
       
        case {'struct','dataset'}
         
          switch fieldTypes{j}
           
            case 'cell'
         
              tmp = data.(sflds{j}){i};
         
            case 'double'
             
              tmp = data.(sflds{j})(i);
             
            case 'char'
             
              tmp = data.(sflds{j})(i,:);
             
          end
       
      end  
     
      %Check for null values and setNull if applicable
      if (isa(tmp,'double')) & ...
         ((isnan(tmp) | (isempty(tmp) & isempty(nnw))) | (~isempty(nnw) & ~isempty(tmp) & tmp == nnw) | (isnan(tmp) & isnan(nnw)))  %#ok
         
         StatementObject.setNull(j,a(j).typeValue)
       
      elseif (isnumeric(tmp) && isempty(tmp))
       
        % Insert numeric null (for binary objects), using -4 fails
        StatementObject.setNull(j,7)
     
      elseif (isa(tmp,'char')) && ...
             ((isempty(tmp) && isempty(nsw)) || strcmp(tmp,nsw))
     
         StatementObject.setNull(j,a(j).typeValue)
     
      else
       
        switch a(j).typeValue
         
          case -7
            StatementObject.setBoolean(j,tmp)  %BIT
          case -6
            StatementObject.setByte(j,tmp)  %TINYINT
          case -5
            StatementObject.setLong(j,tmp)  %BIGINT
          case {-4, -3, 2004}
            StatementObject.setBytes(j,tmp)  %LONGVARBINARY, VARBINARY
          case {-10, -9, -8, -1, 1, 12}
            StatementObject.setString(j,java.lang.String(tmp))  %CHAR, LONGVARCHAR, VARCHAR
          case {2, 3, 7}
            StatementObject.setDouble(j,tmp)  %NUMERIC, DECIMAL, REAL
          case 4
            StatementObject.setInt(j,tmp)  %INTEGER
          case 5
            StatementObject.setShort(j,tmp)  %SMALLINT
          case 6
            StatementObject.setDouble(j,tmp)  %FLOAT
          case 8
            StatementObject.setDouble(j,tmp)  %DOUBLE
          case 91
            dt = datevec(tmp);
            StatementObject.setDate(j,java.sql.Date(dt(1)-1900,dt(2)-1,dt(3)))  %DATE
          case 92
            tt = datevec(tmp);
            StatementObject.setTime(j,java.sql.Time(tt(4),tt(5),tt(6)))  %TIME
          case 93
            ts = datevec(tmp);
            %Need whole second value to calculate nanosecond value
            secs = floor(ts(6));
            nanosecs = (ts(6) - secs) * 1000000000;
            StatementObject.setTimestamp(j,java.sql.Timestamp(ts(1)-1900,ts(2)-1,ts(3),ts(4),ts(5),secs,nanosecs))  %TIMESTAMP
          case {-2,1111}
            error('database:fastinsert:unsupportedDatatype',['Unsupported data type in field ' fieldNames{j}])
          otherwise
            StatementObject.setObject(j,tmp);   %OBJECT
           
        end   %End of switch
      end  %End of datatype and null value check
    end  %End of j loop

    % Add parameters to statement object
    StatementObject.addBatch;
 
end  % End of numberOfRows loop

%Execute prepared statement batch
StatementObject.executeBatch; HIER TRITT DER FEHLER AUF!!!!

close(StatementObject)

 


Meiner Meinung nach ist das sql-Statment korrekt, die DB-Tabelle existiert mit diesen Attributen.
An anderen Stellen benutze ich fastinsert.m ebenfalls (diverse Kombinationen von DBs, Tabellen, Attributen, read/write) ohne Probleme.

Im Anhang befindet sich ein screenshot meines workspace.

Ich weiss nicht wo ich anfangen soll den Fahler zu suchen. Ich denke meine Übergabeparameter sind korrekt.
Code:
StatementObject.addBatch;
Lässt sich nicht mittels debugger untersuchen.

Vielen Dabk für eure Hilfe, Lloyd

workspace.jpg
 Beschreibung:

Download
 Dateiname:  workspace.jpg
 Dateigröße:  69.3 KB
 Heruntergeladen:  650 mal
Private Nachricht senden Benutzer-Profile anzeigen


Titus
Forum-Meister

Forum-Meister


Beiträge: 871
Anmeldedatum: 19.07.07
Wohnort: Aachen
Version: ---
     Beitrag Verfasst am: 02.11.2011, 15:38     Titel:
  Antworten mit Zitat      
Hallo Lloyd,

tritt der Fehler auch auf, wenn Du statt fastinsert die Funktion insert (mit selben Parametern) verwendest?

Titus
Private Nachricht senden Benutzer-Profile anzeigen
 
Lloyd Blankfein
Themenstarter

Forum-Century

Forum-Century



Beiträge: 149
Anmeldedatum: 23.02.11
Wohnort: ---
Version: ---
     Beitrag Verfasst am: 08.11.2011, 12:10     Titel:
  Antworten mit Zitat      
Hallo Titus,

hier tritt ein ähnlicher Fehler auf:


??? Error using ==> ParamDAO.ParamDAO>ParamDAO.setParam at 155
[Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement.

Error in ==> WOverview>pb_details_ov_Callback at 110
ParamDAO.setParam(selectedParameter.Parameter_ID);

Error in ==> gui_mainfcn at 96
feval(varargin{:});

Error in ==> WOverview at 16
gui_mainfcn(gui_State, varargin{:});

Error in ==> @(hObject,eventdata)WOverview('pb_details_ov_Callback',hObject,eventdata,guidata(hObject))


??? Error using ==> waitfor
Error while evaluating uicontrol Callback


insert ruft die Funktion cursor (toolbox) auf:
Code:

function curs = cursor(connect,sqlQuery,qTimeOut)
%CURSOR Cursor constructor.
%   CURS = CURSOR(CONNECT,SQLQUERY,QTIMEOUT) returns a cursor object.
%   CONNECT is a database connection object, QUERY is a valid SQL query,
%   and QTIMEOUT is the query timeout value.
%
%   This function is called by EXEC and never invoked directly from
%   the MATLAB command line.
%
%   See also FETCH.
 
%   Copyright 1984-2008 The MathWorks, Inc.
%   $Revision: 1.27.4.13 $   $Date: 2009/11/05 16:58:12 $%

%Create parent object for generic methods
dbobj = dbtbx;

% Initialize all the elements of the structure.

curs.Attributes     = [];
curs.Data           = 0 ;
curs.DatabaseObject = [];
curs.RowLimit       = 0;
curs.SQLQuery       = [];
curs.Message        = [];

% These fields will be invisible to the user
curs.Type = 'Database Cursor Object';
curs.ResultSet      = 0 ;
curs.Cursor         = 0 ;
curs.Statement      = 0 ;
curs.Fetch          = 0 ;

if nargin == 0
  curs.Message = 'Function requires connection handle and SQL statement.';
  curs=class(curs,'cursor',dbobj);
  return
end

%Process inputs
curs.DatabaseObject = connect;
curs.SQLQuery       = strtrim(char(sqlQuery));

%
% Test for valid connection handle .. non empty value.
%
 
if (isempty(class(connect.Handle))),
   
 curs.Message = 'Invalid Connection';
 return;
 
end

% Call Constructor
%
     
% Fetch all rows matching the SQL query.

curs.Cursor = com.mathworks.toolbox.database.sqlExec(curs.SQLQuery ,connect.Handle);


if (isempty(class(curs.Cursor))),
   
   curs.Message = 'Invalid SQL statement';
   return;
   
else
 
  % Now execute the sql statement and returns the result set for
  % the open cursor
 
  statementVector = createTheSqlStatement(curs.Cursor);
  status = validStatement(curs.Cursor,statementVector);
 
  % Test for error condition .. if SQL statement is invalid then zero
  % value object handle is returned.
 
 if (status ~= 0)
   
     % Return the valid SQL statement object
     curs.Statement = getValidStatement(curs.Cursor,statementVector);
   
     % Set the query timeout value if given
     if exist('qTimeOut','var')
       curs.Statement.setQueryTimeout(qTimeOut)
     end
     
     % convert string to same case for testing if SELECT present in the
     % SQL command string
     
     if ((isempty(strmatch('UPDATE ',upper(curs.SQLQuery))) == 0) || ...
           (isempty(strmatch('DELETE ',upper(curs.SQLQuery))) == 0) || ...
           (isempty(strmatch('INSERT ',upper(curs.SQLQuery))) == 0) || ...
           (isempty(strmatch('COMMIT ',upper(curs.SQLQuery))) == 0) || ...
           (isempty(strmatch('CREATE ',upper(curs.SQLQuery))) == 0) || ...
           (isempty(strmatch('DROP ',upper(curs.SQLQuery))) == 0) || ...
           (isempty(strmatch('ALTER ',upper(curs.SQLQuery))) == 0) || ...
           (isempty(strmatch('TRUNCATE ',upper(curs.SQLQuery))) == 0) || ...
           (isempty(strmatch('ROLLBACK ',upper(curs.SQLQuery))) == 0)),

       % Doing an INSERT, UPDATE, DELETE,Commit or Rollback operation.
     

HIER
KNALLT
ES!!!!!!!!



      rowsAltered = executeTheSqlStatement(curs.Cursor,curs.Statement);      
      % Check to see if an error value has been returned .. if so get
      % the error message.
     
      if (rowsAltered == -5555)
       
        message = statementErrorMessage(curs.Cursor,curs.Statement);        
        try   %Close statement object if it was created to free resources
          close(curs.Statement);
        catch exception %#ok
        end  
        curs.Cursor         = 0;
        curs.Statement      = 0;
        curs.Message = message;
        return;
       
      end
     
      if (rowsAltered == 0)
       
       if (isempty(findstr('COMMIT',upper(curs.SQLQuery))) ~= 0) && ...
            (isempty(findstr('ROLLBACK',upper(curs.SQLQuery))) ~= 0) && ...
            (isempty(findstr('UPDATE',upper(curs.SQLQuery))) ~= 0)
         
            try   %Close statement object if it was created to free resources
              close(curs.Statement);
            catch exception %#ok
            end  
            curs.Message = statementErrorMessage(curs.Cursor,curs.Statement);
       end
         
      else
       
        % Delete, insert and update SQL operations.
        % Set the resultSet object element to be zero as these operations
        % do not return a result set.        
        curs.ResultSet = 0;
         
      end
     
     else
     
        % Doing a Select, stored procedure or DML query.
     
      % Get the result set.
             
      resultSetVector = executeTheSelectStatement(curs.Cursor,curs.Statement);
      status = validResultSet(curs.Cursor,resultSetVector);
       
      % Test for error condition on SQL select statements .. result set
      % object handle has a zero value.
     
      if (status == 0)  
         
         % Reset the elements to 0          
 
        message = statementErrorMessage(curs.Cursor,curs.Statement);
        try   %Close statement object if it was created to free resources
          close(curs.Statement);
        catch exception %#ok
        end    
        curs.Cursor         = 0 ;
        curs.Statement      = 0 ;
        curs.Message        = message;
        curs=class(curs,'cursor',dbobj);
        return;
       
      else
       
        curs.ResultSet = getValidResultSet(curs.Cursor,resultSetVector);
       
      end
     
     
    end
 
 
 else
 
 
 % Reset the elements to 0          
 
   message = errorCreatingStatement(curs.Cursor);  
   
   curs.Cursor         = 0 ;
   curs.Statement      = 0 ;
   curs.Message        = message;
   curs=class(curs,'cursor',dbobj);
   return;
 end

end

curs = class(curs,'cursor',dbobj);

 


Code:
rowsAltered = executeTheSqlStatement(curs.Cursor,curs.Statement);

Der Rückgabewert hier ist -5555, also läuft offensichtlich etwas falsch. Die Funktion
Code:
executeTheSqlStatement
kann man nicht näher mit dem debugger untersuchen.

Ich verstehe nicht wo das Problem liegt. Wie gesagt die insert statements benutze ich an diversen Stellen ohne Probleme.

Llyod
Private Nachricht senden Benutzer-Profile anzeigen
 
Titus
Forum-Meister

Forum-Meister


Beiträge: 871
Anmeldedatum: 19.07.07
Wohnort: Aachen
Version: ---
     Beitrag Verfasst am: 08.11.2011, 12:26     Titel:
  Antworten mit Zitat      
Hallo Llyod,

mein Vorschlag wäre, an der Stelle, wo es "knallt", den Debugger anhalten lassen, curs.Statement anzeigen lassen, das Statement kopieren und in Microsoft Access direkt als Abfrage eingeben. Vielleicht spuckt Access einen Fehler im Statement aus, der weiterhilft?

Titus
Private Nachricht senden Benutzer-Profile anzeigen
 
Lloyd Blankfein
Themenstarter

Forum-Century

Forum-Century



Beiträge: 149
Anmeldedatum: 23.02.11
Wohnort: ---
Version: ---
     Beitrag Verfasst am: 09.11.2011, 10:00     Titel: Autsch!!!
  Antworten mit Zitat      
Hallo Titus,

danke, das hat geholfen. In der Tabelle gibt es ein Attribut Namens Value. Dummerweise handelt es sich hierbei um ein reserviertes Wort der sql-Syntax. Nun habe ich das Attribut umbenannt und das insert Statement funktioniert einwandfrei.

Oh man, das hat verdammt viel Zeit gekostet. Die Aussagekraft der Fehlermeldungen, aller hierbei involvierten Pakete (Matlab, Java, Acces), ist wirklich unter aller Sau!!!

Was mich wundert: Im select Statement welches diese Tabelle ebenfalls ausliest, tauchte Value ebenfalls auf. Hier gab es keine Probleme.

Vielen Dank & Grüße,
Lloyd
Private Nachricht senden Benutzer-Profile anzeigen
 
Neues Thema eröffnen Neue Antwort erstellen



Einstellungen und Berechtigungen
Beiträge der letzten Zeit anzeigen:

Du kannst Beiträge in dieses Forum schreiben.
Du kannst auf Beiträge in diesem Forum antworten.
Du kannst deine Beiträge in diesem Forum nicht bearbeiten.
Du kannst deine Beiträge in diesem Forum nicht löschen.
Du kannst an Umfragen in diesem Forum nicht mitmachen.
Du kannst Dateien in diesem Forum posten
Du kannst Dateien in diesem Forum herunterladen
.





 Impressum  | Nutzungsbedingungen  | Datenschutz | FAQ | goMatlab RSS Button RSS

Hosted by:


Copyright © 2007 - 2025 goMatlab.de | Dies ist keine offizielle Website der Firma The Mathworks

MATLAB, Simulink, Stateflow, Handle Graphics, Real-Time Workshop, SimBiology, SimHydraulics, SimEvents, and xPC TargetBox are registered trademarks and The MathWorks, the L-shaped membrane logo, and Embedded MATLAB are trademarks of The MathWorks, Inc.