List of usage examples for java.sql PreparedStatement getWarnings
SQLWarning getWarnings() throws SQLException;
Statement
object. From source file:org.sakaiproject.util.conversion.SchemaConversionController.java
public boolean migrate(DataSource datasource, SchemaConversionHandler convert, SchemaConversionDriver driver) throws SchemaConversionException { // issues:/*from w w w . j av a 2 s.c o m*/ // Data size bigger than max size for this type? // Failure may cause rest of set to fail? boolean alldone = false; Connection connection = null; PreparedStatement selectNextBatch = null; PreparedStatement markNextBatch = null; PreparedStatement completeNextBatch = null; PreparedStatement selectRecord = null; PreparedStatement selectValidateRecord = null; PreparedStatement updateRecord = null; PreparedStatement reportError = null; ResultSet rs = null; try { connection = datasource.getConnection(); connection.setAutoCommit(false); selectNextBatch = connection.prepareStatement(driver.getSelectNextBatch()); markNextBatch = connection.prepareStatement(driver.getMarkNextBatch()); completeNextBatch = connection.prepareStatement(driver.getCompleteNextBatch()); String selectRecordStr = driver.getSelectRecord(); selectRecord = connection.prepareStatement(selectRecordStr); selectValidateRecord = connection.prepareStatement(driver.getSelectValidateRecord()); updateRecord = connection.prepareStatement(driver.getUpdateRecord()); if (reportErrorsInTable) { reportError = connection.prepareStatement(driver.getErrorReportSql()); } // log.info(" +++ updateRecord == " + driver.getUpdateRecord()); // 2. select x at a time rs = selectNextBatch.executeQuery(); List<String> l = new ArrayList<String>(); while (rs.next()) { l.add(rs.getString(1)); } rs.close(); log.info("Migrating " + l.size() + " records of " + nrecords); for (String id : l) { markNextBatch.clearParameters(); markNextBatch.clearWarnings(); markNextBatch.setString(1, id); if (markNextBatch.executeUpdate() != 1) { log.warn(" --> Failed to mark id [" + id + "][" + id.length() + "] for processing "); insertErrorReport(reportError, id, driver.getHandler(), "Unable to mark this record for processing"); } } int count = 1; for (String id : l) { selectRecord.clearParameters(); selectRecord.setString(1, id); rs = selectRecord.executeQuery(); Object source = null; if (rs.next()) { source = convert.getSource(id, rs); } else { log.warn(" --> Result-set is empty for id: " + id + " [" + count + " of " + l.size() + "]"); insertErrorReport(reportError, id, driver.getHandler(), "Result set empty getting source"); } rs.close(); if (source == null) { log.warn(" --> Source is null for id: " + id + " [" + count + " of " + l.size() + "]"); insertErrorReport(reportError, id, driver.getHandler(), "Source null"); } else { try { updateRecord.clearParameters(); if (convert.convertSource(id, source, updateRecord)) { if (updateRecord.executeUpdate() == 1) { selectValidateRecord.clearParameters(); selectValidateRecord.setString(1, id); rs = selectValidateRecord.executeQuery(); Object result = null; if (rs.next()) { result = convert.getValidateSource(id, rs); } convert.validate(id, source, result); } else { log.warn(" --> Failed to update record " + id + " [" + count + " of " + l.size() + "]"); insertErrorReport(reportError, id, driver.getHandler(), "Failed to update record"); } } else { log.warn(" --> Did not update record " + id + " [" + count + " of " + l.size() + "]"); insertErrorReport(reportError, id, driver.getHandler(), "Failed to write update to db"); } rs.close(); } catch (SQLException e) { String msg = " --> Failure converting or validating item " + id + " [" + count + " of " + l.size() + "] \n"; insertErrorReport(reportError, id, driver.getHandler(), "Exception while updating, converting or verifying item"); SQLWarning warnings = updateRecord.getWarnings(); while (warnings != null) { msg += "\t\t\t" + warnings.getErrorCode() + "\t" + warnings.getMessage() + "\n"; warnings = warnings.getNextWarning(); } log.warn(msg, e); updateRecord.clearWarnings(); updateRecord.clearParameters(); } } completeNextBatch.clearParameters(); completeNextBatch.setString(1, id); if (completeNextBatch.executeUpdate() != 1) { log.warn(" --> Failed to mark id " + id + " for processing [" + count + " of " + l.size() + "]"); insertErrorReport(reportError, id, driver.getHandler(), "Unable to complete next batch"); } count++; } if (l.size() == 0) { dropRegisterTable(connection, convert, driver); alldone = true; } connection.commit(); nrecords -= l.size(); } catch (Exception e) { log.error("Failed to perform migration ", e); try { connection.rollback(); log.error(" ==> Rollback Sucessful ", e); } catch (Exception ex) { log.error(" ==> Rollback Failed ", e); } throw new SchemaConversionException( "Schema Conversion has been aborted due to earlier errors, please investigate "); } finally { try { rs.close(); } catch (Exception ex) { log.debug("exception closing rs " + ex); } try { selectNextBatch.close(); } catch (Exception ex) { log.debug("exception closing selectNextBatch " + ex); } try { markNextBatch.close(); } catch (Exception ex) { log.debug("exception closing markNextBatch " + ex); } try { completeNextBatch.close(); } catch (Exception ex) { log.debug("exception closing completeNextBatch " + ex); } try { selectRecord.close(); } catch (Exception ex) { log.debug("exception closing selectRecord " + ex); } try { selectValidateRecord.close(); } catch (Exception ex) { log.debug("exception closing selectValidateRecord " + ex); } try { updateRecord.close(); } catch (Exception ex) { log.debug("exception closing updateRecord " + ex); } if (reportError != null) { try { reportError.close(); } catch (Exception ex) { log.debug("exception closing reportError " + ex); } } try { connection.close(); } catch (Exception ex) { log.debug("Exception closing connection " + ex); } } return !alldone; }
From source file:org.springframework.jdbc.core.JdbcTemplate.java
public Object execute(PreparedStatementCreator psc, PreparedStatementCallback action) { //??//from w w w . ja v a2 s. com Connection con = DataSourceUtils.getConnection(getDataSource()); PreparedStatement ps = null; try { Connection conToUse = con; if (this.nativeJdbcExtractor != null && this.nativeJdbcExtractor.isNativeConnectionNecessaryForNativePreparedStatements()) { conToUse = this.nativeJdbcExtractor.getNativeConnection(con); } ps = psc.createPreparedStatement(conToUse); DataSourceUtils.applyTransactionTimeout(ps, getDataSource()); PreparedStatement psToUse = ps; if (this.nativeJdbcExtractor != null) { psToUse = this.nativeJdbcExtractor.getNativePreparedStatement(ps); } // Object result = action.doInPreparedStatement(psToUse); SQLWarning warning = ps.getWarnings(); //??? throwExceptionOnWarningIfNotIgnoringWarnings(warning); return result; } catch (SQLException ex) { throw getExceptionTranslator().translate("executing PreparedStatementCallback [" + psc + "]", getSql(psc), ex); } finally {//? if (psc instanceof ParameterDisposer) { ((ParameterDisposer) psc).cleanupParameters(); } JdbcUtils.closeStatement(ps); DataSourceUtils.closeConnectionIfNecessary(con, getDataSource()); } }
From source file:org.springframework.jdbc.core.JdbcTemplateTests.java
public void testUpdateCount() throws Exception { final String sql = "UPDATE INVOICE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?"; int idParam = 11111; MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class); PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock(); mockPreparedStatement.setInt(1, idParam); ctrlPreparedStatement.setVoidCallable(); mockPreparedStatement.executeUpdate(); ctrlPreparedStatement.setReturnValue(1); if (debugEnabled) { mockPreparedStatement.getWarnings(); ctrlPreparedStatement.setReturnValue(null); }// www . j a v a2s . c o m mockPreparedStatement.close(); ctrlPreparedStatement.setVoidCallable(); mockConnection.prepareStatement(sql); ctrlConnection.setReturnValue(mockPreparedStatement); ctrlPreparedStatement.replay(); replay(); Dispatcher d = new Dispatcher(idParam, sql); JdbcTemplate template = new JdbcTemplate(mockDataSource); int rowsAffected = template.update(d); assertTrue("1 update affected 1 row", rowsAffected == 1); /* d = new Dispatcher(idParam); rowsAffected = template.update(d); assertTrue("bogus update affected 0 rows", rowsAffected == 0); */ ctrlPreparedStatement.verify(); }
From source file:org.springframework.jdbc.core.JdbcTemplateTests.java
private void doTestStrings(JdbcTemplateCallback jdbcTemplateCallback, boolean usePreparedStatement, Integer fetchSize, Integer maxRows, Integer queryTimeout, Object argument) throws Exception { String sql = "SELECT FORENAME FROM CUSTMR"; String[] results = { "rod", "gary", " portia" }; class StringHandler implements RowCallbackHandler { private List list = new LinkedList(); public void processRow(ResultSet rs) throws SQLException { list.add(rs.getString(1));// w w w.j av a2s . c o m } public String[] getStrings() { return (String[]) list.toArray(new String[list.size()]); } } MockControl ctrlResultSet = MockControl.createControl(ResultSet.class); ResultSet mockResultSet = (ResultSet) ctrlResultSet.getMock(); mockResultSet.next(); ctrlResultSet.setReturnValue(true); mockResultSet.getString(1); ctrlResultSet.setReturnValue(results[0]); mockResultSet.next(); ctrlResultSet.setReturnValue(true); mockResultSet.getString(1); ctrlResultSet.setReturnValue(results[1]); mockResultSet.next(); ctrlResultSet.setReturnValue(true); mockResultSet.getString(1); ctrlResultSet.setReturnValue(results[2]); mockResultSet.next(); ctrlResultSet.setReturnValue(false); mockResultSet.close(); ctrlResultSet.setVoidCallable(); MockControl ctrlStatement = MockControl.createControl(PreparedStatement.class); PreparedStatement mockStatement = (PreparedStatement) ctrlStatement.getMock(); if (fetchSize != null) { mockStatement.setFetchSize(fetchSize.intValue()); } if (maxRows != null) { mockStatement.setMaxRows(maxRows.intValue()); } if (queryTimeout != null) { mockStatement.setQueryTimeout(queryTimeout.intValue()); } if (argument != null) { mockStatement.setObject(1, argument); } if (usePreparedStatement) { mockStatement.executeQuery(); } else { mockStatement.executeQuery(sql); } ctrlStatement.setReturnValue(mockResultSet); if (debugEnabled) { mockStatement.getWarnings(); ctrlStatement.setReturnValue(null); } mockStatement.close(); ctrlStatement.setVoidCallable(); if (usePreparedStatement) { mockConnection.prepareStatement(sql); } else { mockConnection.createStatement(); } ctrlConnection.setReturnValue(mockStatement); ctrlResultSet.replay(); ctrlStatement.replay(); replay(); StringHandler sh = new StringHandler(); JdbcTemplate template = new JdbcTemplate(); template.setDataSource(mockDataSource); if (fetchSize != null) { template.setFetchSize(fetchSize.intValue()); } if (maxRows != null) { template.setMaxRows(maxRows.intValue()); } if (queryTimeout != null) { template.setQueryTimeout(queryTimeout.intValue()); } jdbcTemplateCallback.doInJdbcTemplate(template, sql, sh); // Match String[] forenames = sh.getStrings(); assertTrue("same length", forenames.length == results.length); for (int i = 0; i < forenames.length; i++) { assertTrue("Row " + i + " matches", forenames[i].equals(results[i])); } ctrlResultSet.verify(); ctrlStatement.verify(); }
From source file:org.springframework.jdbc.core.JdbcTemplateTests.java
public void testLeaveConnectionOpenOnRequest() throws Exception { String sql = "SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3"; MockControl ctrlResultSet = MockControl.createControl(ResultSet.class); ResultSet mockResultSet = (ResultSet) ctrlResultSet.getMock(); ctrlResultSet = MockControl.createControl(ResultSet.class); mockResultSet = (ResultSet) ctrlResultSet.getMock(); mockResultSet.next();/*from w ww . j a v a2 s . c om*/ ctrlResultSet.setReturnValue(false); mockResultSet.close(); ctrlResultSet.setVoidCallable(); MockControl ctrlStatement = MockControl.createControl(PreparedStatement.class); PreparedStatement mockStatement = (PreparedStatement) ctrlStatement.getMock(); ctrlStatement = MockControl.createControl(PreparedStatement.class); mockStatement = (PreparedStatement) ctrlStatement.getMock(); mockStatement.executeQuery(sql); ctrlStatement.setReturnValue(mockResultSet); if (debugEnabled) { mockStatement.getWarnings(); ctrlStatement.setReturnValue(null); } mockStatement.close(); ctrlStatement.setVoidCallable(); mockConnection.isClosed(); ctrlConnection.setReturnValue(false, 2); mockConnection.createStatement(); ctrlConnection.setReturnValue(mockStatement); // if close is called entire test will fail mockConnection.close(); ctrlConnection.setDefaultThrowable(new RuntimeException()); ctrlResultSet.replay(); ctrlStatement.replay(); replay(); SingleConnectionDataSource scf = new SingleConnectionDataSource(mockDataSource.getConnection(), false); JdbcTemplate template2 = new JdbcTemplate(scf, false); RowCountCallbackHandler rcch = new RowCountCallbackHandler(); template2.query(sql, rcch); ctrlResultSet.verify(); ctrlStatement.verify(); }
From source file:org.springframework.jdbc.core.JdbcTemplateTests.java
public void testCloseConnectionOnRequest() throws Exception { String sql = "SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3"; MockControl ctrlResultSet = MockControl.createControl(ResultSet.class); ResultSet mockResultSet = (ResultSet) ctrlResultSet.getMock(); mockResultSet.next();//from w w w .j av a 2 s .c o m ctrlResultSet.setReturnValue(false); mockResultSet.close(); ctrlResultSet.setVoidCallable(); MockControl ctrlStatement = MockControl.createControl(PreparedStatement.class); PreparedStatement mockStatement = (PreparedStatement) ctrlStatement.getMock(); mockStatement.executeQuery(sql); ctrlStatement.setReturnValue(mockResultSet); if (debugEnabled) { mockStatement.getWarnings(); ctrlStatement.setReturnValue(null); } mockStatement.close(); ctrlStatement.setVoidCallable(); mockConnection.createStatement(); ctrlConnection.setReturnValue(mockStatement); ctrlResultSet.replay(); ctrlStatement.replay(); replay(); JdbcTemplate template = new JdbcTemplate(mockDataSource); RowCountCallbackHandler rcch = new RowCountCallbackHandler(); template.query(sql, rcch); ctrlResultSet.verify(); ctrlStatement.verify(); }
From source file:org.springframework.jdbc.core.JdbcTemplateTests.java
/** * Test that we see a runtime exception come back. *///from w w w . j av a 2 s . co m public void testExceptionComesBack() throws Exception { final String sql = "SELECT ID FROM CUSTMR"; final RuntimeException rex = new RuntimeException("What I want to see"); MockControl ctrlResultSet = MockControl.createControl(ResultSet.class); ResultSet mockResultSet = (ResultSet) ctrlResultSet.getMock(); mockResultSet.next(); ctrlResultSet.setReturnValue(true); mockResultSet.close(); ctrlResultSet.setVoidCallable(); MockControl ctrlStatement = MockControl.createControl(PreparedStatement.class); PreparedStatement mockStatement = (PreparedStatement) ctrlStatement.getMock(); mockStatement.executeQuery(sql); ctrlStatement.setReturnValue(mockResultSet); if (debugEnabled) { mockStatement.getWarnings(); ctrlStatement.setReturnValue(null); } mockStatement.close(); ctrlStatement.setVoidCallable(); mockConnection.createStatement(); ctrlConnection.setReturnValue(mockStatement); ctrlResultSet.replay(); ctrlStatement.replay(); replay(); JdbcTemplate template = new JdbcTemplate(mockDataSource); try { template.query(sql, new RowCallbackHandler() { public void processRow(ResultSet rs) { throw rex; } }); fail("Should have thrown exception"); } catch (RuntimeException ex) { assertTrue("Wanted same exception back, not " + ex, ex == rex); } }
From source file:org.springframework.jdbc.core.JdbcTemplateTests.java
/** * Test update with dynamic SQL.//from w ww .ja va 2 s . co m */ public void testSqlUpdateWithArguments() throws Exception { final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ? and PR = ?"; int rowsAffected = 33; MockControl ctrlStatement = MockControl.createControl(PreparedStatement.class); PreparedStatement mockStatement = (PreparedStatement) ctrlStatement.getMock(); mockStatement.setObject(1, new Integer(4)); ctrlStatement.setVoidCallable(); mockStatement.setObject(2, new Float(1.4142), Types.NUMERIC, 2); ctrlStatement.setVoidCallable(); mockStatement.executeUpdate(); ctrlStatement.setReturnValue(33); if (debugEnabled) { mockStatement.getWarnings(); ctrlStatement.setReturnValue(null); } mockStatement.close(); ctrlStatement.setVoidCallable(); mockConnection.prepareStatement(sql); ctrlConnection.setReturnValue(mockStatement); ctrlStatement.replay(); replay(); JdbcTemplate template = new JdbcTemplate(mockDataSource); int actualRowsAffected = template.update(sql, new Object[] { new Integer(4), new SqlParameterValue(Types.NUMERIC, 2, new Float(1.4142)) }); assertTrue("Actual rows affected is correct", actualRowsAffected == rowsAffected); ctrlStatement.verify(); }
From source file:org.springframework.jdbc.core.JdbcTemplateTests.java
public void testBatchUpdateWithPreparedStatement() throws Exception { final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?"; final int[] ids = new int[] { 100, 200 }; final int[] rowsAffected = new int[] { 1, 2 }; MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class); PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock(); mockPreparedStatement.getConnection(); ctrlPreparedStatement.setReturnValue(mockConnection); mockPreparedStatement.setInt(1, ids[0]); ctrlPreparedStatement.setVoidCallable(); mockPreparedStatement.addBatch();/* w ww .jav a2s. c o m*/ ctrlPreparedStatement.setVoidCallable(); mockPreparedStatement.setInt(1, ids[1]); ctrlPreparedStatement.setVoidCallable(); mockPreparedStatement.addBatch(); ctrlPreparedStatement.setVoidCallable(); mockPreparedStatement.executeBatch(); ctrlPreparedStatement.setReturnValue(rowsAffected); if (debugEnabled) { mockPreparedStatement.getWarnings(); ctrlPreparedStatement.setReturnValue(null); } mockPreparedStatement.close(); ctrlPreparedStatement.setVoidCallable(); MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class); DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock(); mockDatabaseMetaData.getDatabaseProductName(); ctrlDatabaseMetaData.setReturnValue("MySQL"); mockDatabaseMetaData.supportsBatchUpdates(); ctrlDatabaseMetaData.setReturnValue(true); mockConnection.prepareStatement(sql); ctrlConnection.setReturnValue(mockPreparedStatement); mockConnection.getMetaData(); ctrlConnection.setReturnValue(mockDatabaseMetaData, 2); ctrlPreparedStatement.replay(); ctrlDatabaseMetaData.replay(); replay(); BatchPreparedStatementSetter setter = new BatchPreparedStatementSetter() { public void setValues(PreparedStatement ps, int i) throws SQLException { ps.setInt(1, ids[i]); } public int getBatchSize() { return ids.length; } }; JdbcTemplate template = new JdbcTemplate(mockDataSource, false); int[] actualRowsAffected = template.batchUpdate(sql, setter); assertTrue("executed 2 updates", actualRowsAffected.length == 2); assertEquals(rowsAffected[0], actualRowsAffected[0]); assertEquals(rowsAffected[1], actualRowsAffected[1]); ctrlPreparedStatement.verify(); ctrlDatabaseMetaData.verify(); }
From source file:org.springframework.jdbc.core.JdbcTemplateTests.java
public void testInterruptibleBatchUpdate() throws Exception { final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = ?"; final int[] ids = new int[] { 100, 200 }; final int[] rowsAffected = new int[] { 1, 2 }; MockControl ctrlPreparedStatement = MockControl.createControl(PreparedStatement.class); PreparedStatement mockPreparedStatement = (PreparedStatement) ctrlPreparedStatement.getMock(); mockPreparedStatement.getConnection(); ctrlPreparedStatement.setReturnValue(mockConnection); mockPreparedStatement.setInt(1, ids[0]); ctrlPreparedStatement.setVoidCallable(); mockPreparedStatement.addBatch();/*from w w w .j av a2 s. c om*/ ctrlPreparedStatement.setVoidCallable(); mockPreparedStatement.setInt(1, ids[1]); ctrlPreparedStatement.setVoidCallable(); mockPreparedStatement.addBatch(); ctrlPreparedStatement.setVoidCallable(); mockPreparedStatement.executeBatch(); ctrlPreparedStatement.setReturnValue(rowsAffected); if (debugEnabled) { mockPreparedStatement.getWarnings(); ctrlPreparedStatement.setReturnValue(null); } mockPreparedStatement.close(); ctrlPreparedStatement.setVoidCallable(); MockControl ctrlDatabaseMetaData = MockControl.createControl(DatabaseMetaData.class); DatabaseMetaData mockDatabaseMetaData = (DatabaseMetaData) ctrlDatabaseMetaData.getMock(); mockDatabaseMetaData.getDatabaseProductName(); ctrlDatabaseMetaData.setReturnValue("MySQL"); mockDatabaseMetaData.supportsBatchUpdates(); ctrlDatabaseMetaData.setReturnValue(true); mockConnection.prepareStatement(sql); ctrlConnection.setReturnValue(mockPreparedStatement); mockConnection.getMetaData(); ctrlConnection.setReturnValue(mockDatabaseMetaData, 2); ctrlPreparedStatement.replay(); ctrlDatabaseMetaData.replay(); replay(); BatchPreparedStatementSetter setter = new InterruptibleBatchPreparedStatementSetter() { public void setValues(PreparedStatement ps, int i) throws SQLException { if (i < ids.length) { ps.setInt(1, ids[i]); } } public int getBatchSize() { return 1000; } public boolean isBatchExhausted(int i) { return (i >= ids.length); } }; JdbcTemplate template = new JdbcTemplate(mockDataSource, false); int[] actualRowsAffected = template.batchUpdate(sql, setter); assertTrue("executed 2 updates", actualRowsAffected.length == 2); assertEquals(rowsAffected[0], actualRowsAffected[0]); assertEquals(rowsAffected[1], actualRowsAffected[1]); ctrlPreparedStatement.verify(); ctrlDatabaseMetaData.verify(); }