Example usage for java.sql PreparedStatement getWarnings

List of usage examples for java.sql PreparedStatement getWarnings

Introduction

In this page you can find the example usage for java.sql PreparedStatement getWarnings.

Prototype

SQLWarning getWarnings() throws SQLException;

Source Link

Document

Retrieves the first warning reported by calls on this Statement object.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    conn.setAutoCommit(false);//w  w  w .  j  a v a  2s . c om
    Statement st = conn.createStatement();

    st.executeUpdate("create table survey (id int, name VARCHAR(30) );");

    String INSERT_RECORD = "insert into survey(id, name) values(?,?)";

    PreparedStatement pstmt = conn.prepareStatement(INSERT_RECORD);

    pstmt.setInt(1, 1);
    pstmt.setString(2, "name");
    pstmt.executeUpdate();

    // Get warnings on PreparedStatement object
    SQLWarning warning = pstmt.getWarnings();
    while (warning != null) {
        // Process statement warnings...
        String message = warning.getMessage();
        String sqlState = warning.getSQLState();
        int errorCode = warning.getErrorCode();
        warning = warning.getNextWarning();
    }

    ResultSet rs = st.executeQuery("SELECT * FROM survey");
    outputResultSet(rs);

    rs.close();
    st.close();
    conn.close();
}

From source file:com.splicemachine.derby.impl.sql.execute.operations.InsertOperationIT.java

@Test
public void testDataTruncationWarningIsEmitted() throws Exception {
    PreparedStatement ps = methodWatcher.prepareStatement("insert into WARNING values cast(? as char(1))");
    ps.setString(1, "12");
    int updated = ps.executeUpdate();
    Assert.assertEquals("Incorrect number of rows updated!", 1, updated);

    SQLWarning warning = ps.getWarnings();
    String sqlState = warning.getSQLState();
    Assert.assertEquals("Incorrect warning code returned!", "01004", sqlState);
}

From source file:com.xqdev.sql.MLSQL.java

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/xml");

    Namespace sql = Namespace.getNamespace("sql", "http://xqdev.com/sql");
    Document responseDoc = new Document();
    Element root = new Element("result", sql);
    Element meta = new Element("meta", sql);
    responseDoc.setRootElement(root);/*from ww w. ja  v a 2 s  . c o  m*/
    root.addContent(meta);

    Document requestDoc = null;
    try {
        // Normally the request comes via the post body,
        // but we let you bookmark w/ a query string
        String postbody = req.getParameter("postbody");
        if (postbody != null) {
            SAXBuilder builder = new SAXBuilder();
            requestDoc = builder.build(new StringReader(postbody));
        } else {
            InputStream in = req.getInputStream();
            SAXBuilder builder = new SAXBuilder();
            requestDoc = builder.build(in);
        }
    } catch (Exception e) {
        addExceptions(meta, e);
        // Now write the error and return
        OutputStream out = res.getOutputStream();
        new XMLOutputter().output(responseDoc, out);
        out.flush();
        return;
    }

    Connection con = null;
    try {
        Namespace[] namespaces = new Namespace[] { sql };
        XPathHelper xpath = new XPathHelper(requestDoc, namespaces);

        String type = xpath.getString("/sql:request/sql:type");
        String query = xpath.getString("/sql:request/sql:query");
        int maxRows = xpath.getInt("/sql:request/sql:execute-options/sql:max-rows", -1);
        int queryTimeout = xpath.getInt("/sql:request/sql:execute-options/sql:query-timeout", -1);
        int maxFieldSize = xpath.getInt("/sql:request/sql:execute-options/sql:max-field-size", -1);
        List<Element> params = xpath
                .getElements("/sql:request/sql:execute-options/sql:parameters/sql:parameter");

        con = pool.getConnection();

        PreparedStatement stmt = null;

        if (type.equalsIgnoreCase("procedure")) {
            stmt = con.prepareCall(query);
        } else {
            // Note this call depends on JDBC 3.0 (accompanying Java 1.4).
            // The call without the 2nd argument would work on earlier JVMs,
            // you just won't catch any generated keys.
            stmt = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
        }
        configureStatement(stmt, maxRows, queryTimeout, maxFieldSize);
        parameterizeStatement(stmt, params);

        if (type.equalsIgnoreCase("select")) {
            try {
                ResultSet rs = stmt.executeQuery();
                addWarnings(meta, stmt.getWarnings());
                addResultSet(root, rs);
            } catch (SQLException e) {
                addExceptions(meta, e);
                Log.log(e);
            }
        } else if (type.equalsIgnoreCase("update")) {
            try {
                int count = stmt.executeUpdate();
                addWarnings(meta, stmt.getWarnings());
                addUpdateCount(meta, count);
                try {
                    addGeneratedKeys(meta, stmt.getGeneratedKeys());
                } catch (SQLException e) {
                    // Generated keys are available on INSERT calls but not UPDATE calls
                    // So catch and eat the exception that Oracle (and maybe others) will throw
                }
            } catch (SQLException e) {
                addExceptions(meta, e);
            }
        } else if (type.equalsIgnoreCase("procedure")) {
            boolean isResultSet = stmt.execute();
            if (isResultSet) {
                addResultSet(root, stmt.getResultSet());
                addOutParam(root, stmt, params);
            } else {
                addOutParam(root, stmt, params);
            }
        } else {
            try {
                boolean isResultSet = stmt.execute();
                addWarnings(meta, stmt.getWarnings());
                if (isResultSet) {
                    addResultSet(root, stmt.getResultSet());
                } else {
                    addUpdateCount(meta, stmt.getUpdateCount());
                    addGeneratedKeys(meta, stmt.getGeneratedKeys());
                }
            } catch (SQLException e) {
                addExceptions(meta, e);
            }
        }
        // Close the statement holding the connection to the JDBC Server
        stmt.close();
    } catch (Exception e) {
        addExceptions(meta, e);
    } finally {
        if (con != null)
            pool.returnConnection(con);
    }

    OutputStream out = res.getOutputStream();
    new XMLOutputter().output(responseDoc, out);
    out.flush();
}

From source file:org.horizontaldb.integration.InterceptorMockEnvironmentTest.java

@Test
public void shouldValidateMultiLevelShardedCalls() throws SQLException {
    ConversationRegistry mockRegistry = EasyMock.createMock(ConversationRegistry.class);
    TenantContext mockTenantContext = EasyMock.createMock(TenantContext.class);
    org.apache.tomcat.jdbc.pool.DataSource mockDataSource = EasyMock
            .createMock(org.apache.tomcat.jdbc.pool.DataSource.class);
    DataSourceResource mockDataSourceResource = new DataSourceResource(mockDataSource);
    ShardBeanResolver mockShardBeanResolver = EasyMock.createMock(ShardBeanResolver.class);
    ShardBeanEnricher mockShardBeanEnricher = EasyMock.createMock(ShardBeanEnricher.class);
    Connection mockConnection = EasyMock.createMock(Connection.class);
    PreparedStatement mockStatement = EasyMock.createMock(PreparedStatement.class);
    ResultSet mockResultset = EasyMock.createMock(ResultSet.class);

    conversationRegistryMockProxy.setMockRegistry(mockRegistry);
    tenantContextMockProxy.setMockTenantContext(mockTenantContext);
    dataSourceFactoryMockProxy.setMockDataSourceResource(mockDataSourceResource);
    shardBeanResolverMockProxy.setMockResolver(mockShardBeanResolver);
    shardBeanEnricherMockProxy.setMockEnricher(mockShardBeanEnricher);

    // This is the protocol that the interceptors should follow during a sharded call
    mockRegistry.startConversation(testUserHelper.getJoeToken());
    expect(mockRegistry.hasConversation(TestUser.JOE.name())).andReturn(true);
    expect(mockTenantContext.resolveCurrentTenantIdentifier()).andReturn(TestUser.JOE.name());
    mockRegistry.addResource(TestUser.JOE.name(), mockDataSourceResource);

    // resolve Dao for TestServiceTwo
    expect(mockShardBeanResolver.getBean(same(PersonDao.class), anyObject(ShardContext.class))).andReturn(null);
    mockRegistry.addResource(same(TestUser.JOE.name()), anyObject(PersonDao.class));
    mockShardBeanEnricher.setup(anyObject(PersonDao.class), anyObject(ShardContext.class));
    mockShardBeanEnricher.tearDown(anyObject(PersonDao.class), anyObject(ShardContext.class));

    // Hibernate transaction flow
    expect(mockDataSource.getConnection()).andReturn(mockConnection);
    mockConnection.setReadOnly(true);/*  w w  w . j av a  2 s.c  o m*/
    expect(mockConnection.getAutoCommit()).andReturn(false);
    expect(mockConnection.prepareStatement(anyObject(String.class))).andReturn(mockStatement);
    expect(mockStatement.executeQuery()).andReturn(mockResultset);
    expect(mockStatement.getWarnings()).andReturn(null);
    mockStatement.clearWarnings();
    expect(mockStatement.getMaxRows()).andReturn(0);
    expect(mockStatement.getQueryTimeout()).andReturn(0);
    expect(mockResultset.next()).andReturn(true);
    expect(mockResultset.next()).andReturn(false);
    expect(mockResultset.getLong(anyObject(String.class))).andReturn(0l);
    expect(mockResultset.wasNull()).andReturn(false);
    expect(mockResultset.getLong(anyObject(String.class))).andReturn(0l);
    expect(mockResultset.wasNull()).andReturn(true);
    expect(mockResultset.getString(anyObject(String.class))).andReturn("mockPerson");
    expect(mockResultset.wasNull()).andReturn(false);
    mockResultset.close();
    mockStatement.close();
    mockConnection.commit();
    // end Hibernate transaction

    // resolve Dao for TestServiceThree
    expect(mockRegistry.hasConversation(TestUser.JOE.name())).andReturn(true);
    expect(mockShardBeanResolver.getBean(same(DepartmentDao.class), anyObject(ShardContext.class)))
            .andReturn(null);
    mockRegistry.addResource(same(TestUser.JOE.name()), anyObject(DepartmentDaoImpl.class));
    mockShardBeanEnricher.setup(anyObject(DepartmentDaoImpl.class), anyObject(ShardContext.class));
    mockShardBeanEnricher.tearDown(anyObject(DepartmentDaoImpl.class), anyObject(ShardContext.class));

    // Hibernate transaction flow
    expect(mockConnection.prepareStatement(anyObject(String.class))).andReturn(mockStatement);
    expect(mockStatement.executeQuery()).andReturn(mockResultset);
    expect(mockStatement.getWarnings()).andReturn(null);
    mockStatement.clearWarnings();
    expect(mockStatement.getMaxRows()).andReturn(0);
    expect(mockStatement.getQueryTimeout()).andReturn(0);
    expect(mockResultset.next()).andReturn(true);
    expect(mockResultset.next()).andReturn(false);
    expect(mockResultset.getLong(anyObject(String.class))).andReturn(0l);
    expect(mockResultset.wasNull()).andReturn(false);
    expect(mockResultset.getString(anyObject(String.class))).andReturn("mockDepartment");
    expect(mockResultset.wasNull()).andReturn(false);
    mockResultset.close();
    mockStatement.close();
    // end Hibernate transaction

    // cleanup after service calls
    mockDataSource.close(true);
    mockRegistry.teardownConversation(testUserHelper.getJoeToken());

    replay(mockRegistry, mockTenantContext, mockShardBeanResolver, mockShardBeanEnricher, mockDataSource,
            mockConnection, mockStatement, mockResultset);

    try {
        testService.authenticate(testUserHelper.getJoeToken());

        testService.callNestedServiceChain(TestUser.JOE.name());
    } finally {
        testService.logoff(testUserHelper.getJoeToken());
    }

    verify(mockRegistry, mockTenantContext, mockShardBeanResolver, mockShardBeanEnricher, mockDataSource,
            mockConnection, mockStatement, mockResultset);
}

From source file:org.horizontaldb.integration.InterceptorMockEnvironmentTest.java

@Test
public void shouldValidateOneLevelShardedCall() throws SQLException {
    ConversationRegistry mockRegistry = EasyMock.createMock(ConversationRegistry.class);
    TenantContext mockTenantContext = EasyMock.createMock(TenantContext.class);
    org.apache.tomcat.jdbc.pool.DataSource mockDataSource = EasyMock
            .createMock(org.apache.tomcat.jdbc.pool.DataSource.class);
    DataSourceResource mockDataSourceResource = new DataSourceResource(mockDataSource);
    ShardBeanResolver mockShardBeanResolver = EasyMock.createMock(ShardBeanResolver.class);
    ShardBeanEnricher mockShardBeanEnricher = EasyMock.createMock(ShardBeanEnricher.class);
    Connection mockConnection = EasyMock.createMock(Connection.class);
    PreparedStatement mockStatement = EasyMock.createMock(PreparedStatement.class);
    ResultSet mockResultset = EasyMock.createMock(ResultSet.class);

    conversationRegistryMockProxy.setMockRegistry(mockRegistry);
    tenantContextMockProxy.setMockTenantContext(mockTenantContext);
    dataSourceFactoryMockProxy.setMockDataSourceResource(mockDataSourceResource);
    shardBeanResolverMockProxy.setMockResolver(mockShardBeanResolver);
    shardBeanEnricherMockProxy.setMockEnricher(mockShardBeanEnricher);

    // This is the protocol that the interceptors should follow during a sharded call
    mockRegistry.startConversation(testUserHelper.getJoeToken());
    expect(mockRegistry.hasConversation(TestUser.JOE.name())).andReturn(true);
    expect(mockTenantContext.resolveCurrentTenantIdentifier()).andReturn(TestUser.JOE.name());
    mockRegistry.addResource(TestUser.JOE.name(), mockDataSourceResource);
    mockRegistry.addResource(same(TestUser.JOE.name()), anyObject(DepartmentDaoImpl.class));
    expect(mockShardBeanResolver.getBean(same(DepartmentDao.class), anyObject(ShardContext.class)))
            .andReturn(null);/*from  w ww.  java 2s .c om*/
    mockShardBeanEnricher.setup(anyObject(DepartmentDaoImpl.class), anyObject(ShardContext.class));
    mockShardBeanEnricher.tearDown(anyObject(DepartmentDaoImpl.class), anyObject(ShardContext.class));
    mockDataSource.close(true);
    mockRegistry.teardownConversation(testUserHelper.getJoeToken());
    // end protocol

    // This is the flow of a Hibernate transaction which is irrelevant, but had to be defined because of the
    // mocked dataSource.
    expect(mockDataSource.getConnection()).andReturn(mockConnection);
    mockConnection.setReadOnly(true);
    expect(mockConnection.getAutoCommit()).andReturn(false);
    expect(mockConnection.prepareStatement(anyObject(String.class))).andReturn(mockStatement);
    expect(mockStatement.executeQuery()).andReturn(mockResultset);
    expect(mockStatement.getWarnings()).andReturn(null);
    mockStatement.clearWarnings();
    expect(mockStatement.getMaxRows()).andReturn(0);
    expect(mockStatement.getQueryTimeout()).andReturn(0);
    expect(mockResultset.next()).andReturn(true);
    expect(mockResultset.next()).andReturn(false);
    expect(mockResultset.getLong(anyObject(String.class))).andReturn(0l);
    expect(mockResultset.wasNull()).andReturn(false);
    mockResultset.close();
    mockStatement.close();
    mockConnection.commit();
    // end Hibernate transaction

    replay(mockRegistry, mockTenantContext, mockShardBeanResolver, mockShardBeanEnricher, mockDataSource,
            mockConnection, mockStatement, mockResultset);

    try {
        ShardContext context = new ShardContext(TestUser.JOE.name());

        testService.authenticate(testUserHelper.getJoeToken());

        Long actualCount = testService.getCountOfDepartments(context);

        assertEquals(0, actualCount.longValue());
    } finally {
        testService.logoff(testUserHelper.getJoeToken());
    }

    verify(mockRegistry, mockTenantContext, mockShardBeanResolver, mockShardBeanEnricher, mockDataSource,
            mockConnection, mockStatement, mockResultset);
}

From source file:edu.ku.brc.specify.config.init.secwiz.UserPanel.java

/**
 * //  ww  w .  j a va2 s.  c  o m
 */
private void saveUserData() {
    boolean hasErrors = false;
    DBMSUserMgr mgr = DBMSUserMgr.getInstance();

    PreparedStatement pStmtSp = null;
    PreparedStatement pStmtAg = null;
    try {
        String dbUserName = properties.getProperty("dbUserName");
        String dbPassword = properties.getProperty("dbPassword");
        String hostName = properties.getProperty("hostName");

        if (mgr.connect(dbUserName, dbPassword, hostName, databaseName)) {
            pStmtSp = mgr.getConnection()
                    .prepareStatement("UPDATE specifyuser SET EMail=?, Password=? WHERE SpecifyUserID = ?");
            pStmtAg = mgr.getConnection().prepareStatement("UPDATE agent SET Email=? WHERE AgentID = ?");

            for (UserData ud : userModel.getUserData()) {
                if (ud.isChanged()) {
                    if (StringUtils.isNotEmpty(ud.getEmail())) {
                        pStmtSp.setString(1, ud.getEmail());
                    } else {
                        pStmtSp.setObject(1, null);
                    }
                    pStmtSp.setString(2, ud.getPassword());
                    pStmtSp.setInt(3, ud.getId());
                    int rv = pStmtSp.executeUpdate();
                    if (rv == 1) {
                        ud.setChanged(false);
                    } else {
                        System.err.println("Error " + pStmtSp.getWarnings());
                    }

                    if (StringUtils.isNotEmpty(ud.getEmail())) {
                        String sql = String.format(
                                "SELECT AgentID FROM agent WHERE SpecifyUserID = %d AND (Email IS NULL OR Email <> '%s')",
                                ud.getId(), ud.getEmail());
                        Vector<Integer> agentIds = BasicSQLUtils.queryForInts(mgr.getConnection(), sql);
                        for (Integer agentId : agentIds) {
                            pStmtAg.setString(1, ud.getEmail());
                            pStmtAg.setInt(2, agentId);
                        }

                        if (pStmtSp.executeUpdate() != 1) {
                            // error
                            hasErrors = true;
                        }
                    }
                }
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (pStmtSp != null)
                pStmtSp.close();
            if (pStmtAg != null)
                pStmtAg.close();
            mgr.close();
        } catch (SQLException e) {
        }
    }

    if (!hasErrors) {
        userModel.setPwdChanged(false);
        userModel.setChanged(false);
        saveBtn.setEnabled(false);
        mkKeysBtn.setEnabled(false);

        if (changedEMail) {
            changedEMail = false;
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    UIRegistry.loadAndPushResourceBundle("specifydbsetupwiz");
                    UIRegistry.showLocalizedMsg(JOptionPane.INFORMATION_MESSAGE, "SEC_EML_TITLE",
                            "SEC_EML_MSG");
                    UIRegistry.popResourceBundle();
                }
            });
        }
    }
}

From source file:nl.nn.adapterframework.jdbc.JdbcQuerySenderBase.java

protected String executeUpdateBlobQuery(PreparedStatement statement, Object message) throws SenderException {
    ResultSet rs = null;//from   w w  w  . j a v a  2  s. c  o m
    try {
        log.debug(getLogPrefix() + "executing an updating BLOB command");
        rs = statement.executeQuery();
        XmlBuilder result = new XmlBuilder("result");
        JdbcUtil.warningsToXml(statement.getWarnings(), result);
        rs.next();
        if (message instanceof Reader) {
            Object blobHandle = getDbmsSupport().getBlobUpdateHandle(rs, blobColumn);
            Reader inReader = (Reader) message;
            Writer writer = JdbcUtil.getBlobWriter(getDbmsSupport(), blobHandle, rs, blobColumn,
                    getBlobCharset(), isBlobsCompressed());
            Misc.readerToWriter(inReader, writer, isCloseInputstreamOnExit());
            writer.close();
            getDbmsSupport().updateBlob(rs, blobColumn, blobHandle);
        } else if (message instanceof InputStream) {
            Object blobHandle = getDbmsSupport().getBlobUpdateHandle(rs, blobColumn);
            InputStream inStream = (InputStream) message;
            if (StringUtils.isNotEmpty(getStreamCharset())) {
                Writer writer = JdbcUtil.getBlobWriter(getDbmsSupport(), blobHandle, rs, blobColumn,
                        getBlobCharset(), isBlobsCompressed());
                Reader reader = new InputStreamReader(inStream, getStreamCharset());
                Misc.readerToWriter(reader, writer, isCloseInputstreamOnExit());
                writer.close();
            } else {
                OutputStream outStream = JdbcUtil.getBlobOutputStream(getDbmsSupport(), blobHandle, rs,
                        blobColumn, isBlobsCompressed());
                Misc.streamToStream(inStream, outStream, isCloseInputstreamOnExit());
                outStream.close();
            }
            getDbmsSupport().updateBlob(rs, blobColumn, blobHandle);
        } else if (message instanceof byte[]) {
            JdbcUtil.putByteArrayAsBlob(getDbmsSupport(), rs, blobColumn, (byte[]) message,
                    isBlobsCompressed());
        } else {
            JdbcUtil.putStringAsBlob(getDbmsSupport(), rs, blobColumn, (String) message, getBlobCharset(),
                    isBlobsCompressed());
        }

        rs.updateRow();
        JdbcUtil.warningsToXml(rs.getWarnings(), result);
        return result.toXML();
    } catch (SQLException sqle) {
        throw new SenderException(getLogPrefix() + "got exception executing an updating BLOB command", sqle);
    } catch (JdbcException e) {
        throw new SenderException(getLogPrefix() + "got exception executing an updating BLOB command", e);
    } catch (IOException e) {
        throw new SenderException(getLogPrefix() + "got exception executing an updating BLOB command", e);
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            log.warn(new SenderException(getLogPrefix() + "got exception closing resultset", e));
        }
    }
}

From source file:nl.nn.adapterframework.jdbc.JdbcQuerySenderBase.java

protected String executeUpdateClobQuery(PreparedStatement statement, Object message) throws SenderException {
    ResultSet rs = null;//from  w  ww.j a v a2 s  .com
    try {
        log.debug(getLogPrefix() + "executing an updating CLOB command");
        rs = statement.executeQuery();
        XmlBuilder result = new XmlBuilder("result");
        JdbcUtil.warningsToXml(statement.getWarnings(), result);
        rs.next();
        if (message instanceof Reader) {
            Object clobHandle = getDbmsSupport().getClobUpdateHandle(rs, clobColumn);
            Reader inReader = (Reader) message;
            Writer writer = getDbmsSupport().getClobWriter(rs, clobColumn, clobHandle);
            Misc.readerToWriter(inReader, writer, isCloseInputstreamOnExit());
            writer.close();
            getDbmsSupport().updateClob(rs, clobColumn, clobHandle);
        } else if (message instanceof InputStream) {
            Object clobHandle = getDbmsSupport().getClobUpdateHandle(rs, clobColumn);
            InputStream inStream = (InputStream) message;
            Reader reader;
            if (StringUtils.isNotEmpty(getStreamCharset())) {
                reader = new InputStreamReader(inStream, getStreamCharset());
            } else {
                reader = new InputStreamReader(inStream);
            }
            Writer writer = getDbmsSupport().getClobWriter(rs, clobColumn, clobHandle);
            Misc.readerToWriter(reader, writer, isCloseInputstreamOnExit());
            writer.close();
            getDbmsSupport().updateClob(rs, clobColumn, clobHandle);
        } else {
            JdbcUtil.putStringAsClob(getDbmsSupport(), rs, clobColumn, (String) message);
        }
        rs.updateRow();
        JdbcUtil.warningsToXml(rs.getWarnings(), result);
        return result.toXML();
    } catch (SQLException sqle) {
        throw new SenderException(getLogPrefix() + "got exception executing an updating CLOB command", sqle);
    } catch (JdbcException e) {
        throw new SenderException(getLogPrefix() + "got exception executing an updating CLOB command", e);
    } catch (IOException e) {
        throw new SenderException(getLogPrefix() + "got exception executing an updating CLOB command", e);
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            log.warn(new SenderException(getLogPrefix() + "got exception closing resultset", e));
        }
    }
}

From source file:org.apache.lens.driver.jdbc.JDBCDriver.java

/**
 * Prepare statment on the database server
 * @param pContext query context//  w ww. ja  v a2s . c  o  m
 * @param calledForEstimate set this to true if this call will use the estimate connection pool
 * @param checkConfigured set this to true if this call needs to check whether JDBC driver is configured
 * @param metricCallStack stack for metrics API
 * @return prepared statement
 * @throws LensException
 */
private PreparedStatement prepareInternal(AbstractQueryContext pContext, boolean calledForEstimate,
        boolean checkConfigured, String metricCallStack) throws LensException {
    // Caller might have already verified configured status and driver query, so we don't have
    // to do this check twice. Caller must set checkConfigured to false in that case.
    if (checkConfigured) {
        if (pContext.getDriverQuery(this) == null) {
            throw new NullPointerException("Null driver query for " + pContext.getUserQuery());
        }
        checkConfigured();
    }

    // Only create a prepared statement and then close it
    MethodMetricsContext sqlRewriteGauge = MethodMetricsFactory.createMethodGauge(pContext.getDriverConf(this),
            true, metricCallStack + COLUMNAR_SQL_REWRITE_GAUGE);
    String rewrittenQuery = rewriteQuery(pContext);
    sqlRewriteGauge.markSuccess();
    MethodMetricsContext jdbcPrepareGauge = MethodMetricsFactory.createMethodGauge(pContext.getDriverConf(this),
            true, metricCallStack + JDBC_PREPARE_GAUGE);

    PreparedStatement stmt = null;
    Connection conn = null;
    try {
        conn = calledForEstimate ? getEstimateConnection() : getConnection();
        stmt = conn.prepareStatement(rewrittenQuery);
        if (!pContext.getDriverConf(this).getBoolean(JDBC_VALIDATE_SKIP_WARNINGS,
                DEFAULT_JDBC_VALIDATE_SKIP_WARNINGS) && stmt.getWarnings() != null) {
            throw new LensException(stmt.getWarnings());
        }
    } catch (SQLException sql) {
        handleJDBCSQLException(sql);
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                log.error("Error closing connection: {}", rewrittenQuery, e);
            }
        }
        jdbcPrepareGauge.markSuccess();
    }
    log.info("Prepared: {}", rewrittenQuery);
    return stmt;
}

From source file:org.rimudb.Table.java

/**
 * Update the database with the newRecord data. Key values from the
 * oldRecord are used. The update is run using the SQL connection con.
 *//*from  w  ww  .  ja v a  2 s . c o  m*/
protected void update(Connection con, Record oldRecord, Record newRecord) throws RimuDBException {
    PreparedStatement stmt = null;
    int statID = 0;
    try {
        List<String> changedPropertyList = newRecord.getModifiedProperties();
        List<String> nulledProperties = oldRecord.getNulledProperties();

        // Throws an exception if one of the changed properties is a PK and its being changed to a null
        tableMetaData.checkForNulledPrimaryKey(newRecord.getModifiedToNullProperties());

        List<String> nullColumnList = tableMetaData.getColumnNamesFromPropertyNames(nulledProperties);

        String sql = sqlStatementCache.getUpdatePKSQL(getOptimisticLocking(), changedPropertyList,
                nullColumnList);
        if (sql == null) {
            sql = sqlAdapter.getPrimaryKeyUpdateStatement(tableMetaData, getTableName(), getOptimisticLocking(),
                    changedPropertyList, nullColumnList);
            sqlStatementCache.addUpdatePKSQL(getOptimisticLocking(), changedPropertyList, nullColumnList, sql);
        }

        // Get the statistic ID
        int loggingType = getDatabase().getDatabaseConfiguration().getLoggingType();
        if (loggingType == DatabaseConfiguration.LOG_STATISTICS) {
            statID = StatisticCollector.getInstance().createStatistic(sql);
        } else if (loggingType == DatabaseConfiguration.LOG_SQL_ONLY) {
            log.info("SQL=" + sql);
        }

        stmt = createPreparedStatement(con, sql, CrudType.UPDATE);

        recordBinder.bindStatementForUpdate(stmt, oldRecord, newRecord, getOptimisticLocking(),
                changedPropertyList);

        if (statID > 0)
            StatisticCollector.getInstance().logEvent(statID, "preparetime");

        int rowsUpdated = stmt.executeUpdate();

        SQLWarning warning = stmt.getWarnings();
        while (warning != null) {
            log.warn(warning.getMessage());
            warning = warning.getNextWarning();
        }

        // If we didn't update a row then the where clause didn't find a record, so we have a stale record
        if (rowsUpdated == 0) {
            // Read the current record from the DB so we can discover the values that are different
            Record currentValue = get(oldRecord.getPrimaryWhereList());
            String changedValues = currentValue.getChangedPropertiesText(oldRecord);
            //            log.error("Record in database: "+currentValue.toKeyPairString());
            //            log.error("Unmodified record in memory: "+oldRecord.toKeyPairString());
            //            log.error("Modified record in memory: "+newRecord.toKeyPairString());
            throw new RecordChangeException(
                    "This record has already been changed by another process. Change was not processed. Changed values: "
                            + changedValues);
        }

        if (statID > 0)
            StatisticCollector.getInstance().logEvent(statID, "executetime");

        if (statID > 0) {
            StatisticCollector.getInstance().logEvent(statID, "processtime");
            if (StatisticCollector.getInstance().exceedsThreshold(statID,
                    getDatabase().getDatabaseConfiguration().getLoggingThreshold())) {
                String text = StatisticCollector.getInstance().formatStatistics(statID,
                        getDatabase().getStatisticFormatter());
                log.info(text);
            }
            StatisticCollector.getInstance().removeID(statID);
        }

    } catch (SQLException e) {

        throw new RimuDBException(e);

    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
            }
            stmt = null;
        }
    }
}