Example usage for java.sql Connection isClosed

List of usage examples for java.sql Connection isClosed

Introduction

In this page you can find the example usage for java.sql Connection isClosed.

Prototype

boolean isClosed() throws SQLException;

Source Link

Document

Retrieves whether this Connection object has been closed.

Usage

From source file:org.sakaiproject.dash.jobs.DashAggregateJob.java

private void closeEventDbConnection(Connection connection) {
    if (getUrl() == null) {
        if (connection != null) {
            sqlService.returnConnection(connection);
        }/*w w w .  j a va 2 s .c o m*/
    } else {
        try {
            if (connection != null && !connection.isClosed()) {
                connection.close();
            }
        } catch (SQLException e) {
            LOG.error("Unable to close connection " + getUrl(), e);
        }
    }
}

From source file:updatePledge.java

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
    // TODO add your handling code here:
    String PledgeID = jComboBox4.getSelectedItem().toString();

    try {/*  www  .  j  ava  2 s.  com*/
        try {
            Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(viewDonors.class.getName()).log(Level.SEVERE, null, ex);
        }
        Connection con;
        con = DriverManager.getConnection(DBcon.Connect(), DBcon.Login(), DBcon.Pass()); //(file path, db login, db password) - since it doesnt have a login, leave it blank

        Statement s = con.createStatement();
        System.out.println("Connection to DB established...");

        ResultSet rs = s.executeQuery("SELECT PaymentFrequency, PayToDate, LastPaymentDate " + "FROM Pledges "
                + "WHERE (Pledges.PledgeID = '" + PledgeID + "')");

        System.out.println("Is connection closed: " + con.isClosed());
        System.out.println("Connection to DB established...");
        while (rs.next()) {

            jComboBox5.setSelectedItem(rs.getString(1));
            jTextField1.setText(rs.getString(2));
            jTextField2.setText(rs.getString(3));

        }

        con.close();
        System.out.println("Is connection closed: " + con.isClosed());
    } catch (SQLException ex) {
        Logger.getLogger(userLogin.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(updatePledge.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.tacitknowledge.util.migration.jdbc.JdbcMigrationLauncher.java

/**
 * Performs the application migration process in one go
 *
 * @param context the database context to run the patches in
 * @return the number of patches applied
 * @throws SQLException       if an unrecoverable database error occurs while working with the patches table.
 * @throws MigrationException if an unrecoverable error occurs during the migration
 *///  w  w w.j  a v a 2s .  com
protected int doMigrations(JdbcMigrationContext context) throws SQLException, MigrationException {
    PatchInfoStore patchTable = createPatchStore(context);

    lockPatchStore(context);

    // Now apply the patches
    int executedPatchCount = 0;
    try {

        // remember the auto-commit state, and turn auto-commit off
        Connection conn = context.getConnection();
        boolean commitState = conn.getAutoCommit();
        conn.setAutoCommit(false);

        // run the migrations
        try {
            executedPatchCount = migrationProcess.doMigrations(patchTable, context);
        }

        // restore autocommit state
        finally {
            if ((conn != null) && !conn.isClosed()) {
                conn.setAutoCommit(commitState);
            }
        }
    } catch (MigrationException me) {
        // If there was any kind of error, we don't want to eat it, but we do
        // want to unlock the patch store. So do that, then re-throw.
        patchTable.unlockPatchStore();
        throw me;
    }

    // Do any post-patch tasks
    try {
        migrationProcess.doPostPatchMigrations(context);
        return executedPatchCount;
    } finally {
        try {
            patchTable.unlockPatchStore();
        } catch (MigrationException e) {
            log.error("Error unlocking patch table: ", e);
        }
    }
}

From source file:edu.ku.brc.specify.tools.webportal.BuildSearchIndex2.java

License:asdf

protected void disConnect(Connection con) throws SQLException {
    if (con != null) {
        if (!con.isClosed()) {
            con.close();// w  w w .  java 2  s.c  om
        }
        con = null;
    }
}

From source file:net.ymate.platform.persistence.jdbc.impl.DefaultSession.java

@SuppressWarnings("unchecked")
public <T extends IEntity> List<T> insert(List<T> entities, Fields filter) throws Exception {
    T _element = entities.get(0);//w w w  . j  a  v a2  s.c o  m
    EntityMeta _meta = EntityMeta.createAndGet(_element.getClass());
    PairObject<Fields, Params> _entity = __doGetEntityFieldAndValues(_meta, _element, filter, true);
    String _insertSql = __dialect.buildInsertSQL(_element.getClass(), __tablePrefix, null, _entity.getKey());
    IBatchUpdateOperator _opt = new BatchUpdateOperator(_insertSql, this.__connectionHolder);
    if (_meta.hasAutoincrement()) {
        // Oracle??
        if (__connectionHolder.getDialect() instanceof OracleDialect) {
            final String[] _ids = _meta.getAutoincrementKeys()
                    .toArray(new String[_meta.getAutoincrementKeys().size()]);
            _opt.setAccessorConfig(
                    new EntityAccessorConfig(_meta, __connectionHolder, (List<IEntity<?>>) entities) {
                        @Override
                        public PreparedStatement getPreparedStatement(Connection conn, String sql)
                                throws SQLException {
                            if (conn != null && !conn.isClosed()) {
                                return conn.prepareStatement(sql, _ids);
                            }
                            return __conn.getConnection().prepareStatement(sql, _ids);
                        }
                    });
        } else {
            _opt.setAccessorConfig(
                    new EntityAccessorConfig(_meta, __connectionHolder, (List<IEntity<?>>) entities));
        }
    }
    for (T entity : entities) {
        SQLBatchParameter _batchParam = SQLBatchParameter.create();
        for (Object _param : __doGetEntityFieldAndValues(_meta, entity, filter, true).getValue().params()) {
            _batchParam.addParameter(_param);
        }
        _opt.addBatchParameter(_batchParam);
    }
    if (__sessionEvent != null) {
        __sessionEvent.onInsertBefore(new SessionEventContext(_opt));
    }
    _opt.execute();
    if (__sessionEvent != null) {
        __sessionEvent.onInsertAfter(new SessionEventContext(_opt));
    }
    return entities;
}

From source file:pivotal.au.se.gemfirexdweb.controller.QueryController.java

@RequestMapping(value = "/query", method = RequestMethod.POST)
public String worksheetAction(@ModelAttribute("queryAttribute") QueryWindow queryAttribute, Model model,
        HttpServletResponse response, HttpServletRequest request, HttpSession session) throws Exception {
    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
    } else {/*from ww  w. j  a  v a 2 s  . com*/
        Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
        if (conn == null) {
            response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
            return null;
        } else {
            if (conn.isClosed()) {
                response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
                return null;
            }
        }

    }

    logger.debug("Received request to action SQL from query worksheet");
    logger.info(queryAttribute);

    UserPref userPrefs = (UserPref) session.getAttribute("prefs");

    ConnectionManager cm = ConnectionManager.getInstance();

    if (queryAttribute.getQuery() != null) {

        if (queryAttribute.getSaveWorksheet().equals("Y")) {
            response.setContentType(SAVE_CONTENT_TYPE);
            response.setHeader("Content-Disposition", "attachment; filename=" + FILENAME);

            ServletOutputStream out = response.getOutputStream();
            out.println(queryAttribute.getQuery());
            out.close();
            return null;
        }

        // retrieve connection
        Connection conn = cm.getConnection(session.getId());
        String query = queryAttribute.getQuery().trim();
        logger.debug("Query = " + query);

        String[] splitQueryStr = spiltQuery(query);

        CommandResult result = new CommandResult();

        if (query.length() > 0) {
            if (splitQueryStr.length == 1) {
                String s = checkForComments(query);
                s = s.trim();

                if (determineQueryType(s).equals("SELECT")) {
                    try {
                        final String explain = queryAttribute.getExplainPlan();
                        if (!explain.equals("N")) {
                            logger.debug("Need to run explain plan.");

                            String explainString = "";

                            if (explain.equals("Y")) {
                                explainString = "explain as xml %s";
                            } else if (explain.equals("T")) {
                                explainString = "explain %s";
                            }

                            String xPlan = QueryUtil.runExplainPlan(conn, String.format(explainString, query));
                            logger.debug("received xPath : " + xPlan);

                            if (explain.equals("Y")) {
                                model.addAttribute("explainresult", xPlan);
                            } else if (explain.equals("T")) {
                                model.addAttribute("explaintxtresult", xPlan);
                            }
                        } else {

                            if (queryAttribute.getShowMember().equals("Y")) {
                                String replace = "select dsid() as \"Member\",";

                                s = query.toLowerCase().replaceFirst("select", replace);
                            }

                            long start = System.currentTimeMillis();
                            Result res = QueryUtil.runQuery(conn, s, userPrefs.getMaxRecordsinSQLQueryWindow());
                            long end = System.currentTimeMillis();

                            double timeTaken = new Double(end - start).doubleValue();
                            DecimalFormat df = new DecimalFormat("#.##");

                            model.addAttribute("queryResults", res);
                            model.addAttribute("query", s);
                            model.addAttribute("querysql", s);
                            if (queryAttribute.getQueryCount().equals("Y")) {
                                model.addAttribute("queryResultCount", res.getRowCount());
                            }

                            if (queryAttribute.getElapsedTime().equals("Y")) {
                                model.addAttribute("elapsedTime", df.format(timeTaken / 1000));
                            }

                            addCommandToHistory(session, userPrefs, s);

                        }
                    } catch (Exception ex) {
                        result.setCommand(s);
                        result.setMessage(ex.getMessage() == null ? "Unable to run query" : ex.getMessage());
                        result.setRows(-1);
                        model.addAttribute("result", result);
                        model.addAttribute("query", s);
                    }
                } else {
                    if (s.length() > 0) {
                        if (determineQueryType(s).equals("COMMIT")) {
                            result = QueryUtil.runCommitOrRollback(conn, true, queryAttribute.getElapsedTime());
                            model.addAttribute("result", result);
                            if (result.getMessage().startsWith("SUCCESS")) {
                                addCommandToHistory(session, userPrefs, s);
                            }
                        } else if (determineQueryType(s).equals("ROLLBACK")) {
                            result = QueryUtil.runCommitOrRollback(conn, false,
                                    queryAttribute.getElapsedTime());
                            model.addAttribute("result", result);
                            if (result.getMessage().startsWith("SUCCESS")) {
                                addCommandToHistory(session, userPrefs, s);
                            }
                        } else if (determineQueryType(s).equals("CALL")) {

                            String procName = getProcName(s);

                            if (procName != null) {
                                String schema = null;

                                int x = procName.indexOf(".");
                                if (x != -1) {
                                    String newProcName = procName.substring((procName.indexOf(".") + 1));
                                    schema = procName.substring(0, (procName.indexOf(".")));
                                    procName = newProcName;
                                } else {
                                    schema = (String) session.getAttribute("schema");
                                }

                                logger.debug("schema for stored procedure = " + schema);
                                logger.debug("call statement called for proc with name " + procName);

                                // need to get schema name to check proc details
                                int numberOfDynamicResultSets = QueryUtil.checkForDynamicResultSetProc(conn,
                                        schema, procName);

                                if (numberOfDynamicResultSets > 0) {
                                    logger.debug("call statement with " + numberOfDynamicResultSets
                                            + " dynamic resultset(s)");
                                    try {
                                        List<Result> procResults = QueryUtil.runStoredprocWithResultSet(conn, s,
                                                userPrefs.getMaxRecordsinSQLQueryWindow(),
                                                numberOfDynamicResultSets);
                                        model.addAttribute("procresults", procResults);
                                        model.addAttribute("callstatement", procName);
                                        model.addAttribute("dynamicresults", numberOfDynamicResultSets);
                                        addCommandToHistory(session, userPrefs, s);
                                    } catch (Exception ex) {
                                        result.setCommand(s);
                                        result.setMessage(ex.getMessage() == null ? "Unable to run query"
                                                : ex.getMessage());
                                        result.setRows(-1);
                                        model.addAttribute("result", result);
                                        model.addAttribute("query", s);
                                    }
                                } else {
                                    result = QueryUtil.runCommand(conn, s, queryAttribute.getElapsedTime());
                                    model.addAttribute("result", result);
                                    if (result.getMessage().startsWith("SUCCESS")) {
                                        addCommandToHistory(session, userPrefs, s);
                                    }
                                }
                            } else {
                                result = QueryUtil.runCommand(conn, s, queryAttribute.getElapsedTime());
                                model.addAttribute("result", result);
                                if (result.getMessage().startsWith("SUCCESS")) {
                                    addCommandToHistory(session, userPrefs, s);
                                }
                            }
                        } else {
                            result = QueryUtil.runCommand(conn, s, queryAttribute.getElapsedTime());
                            model.addAttribute("result", result);
                            if (result.getMessage().startsWith("SUCCESS")) {
                                addCommandToHistory(session, userPrefs, s);
                            }
                        }

                    }
                }

            } else {
                logger.debug("multiple SQL statements need to be executed");
                SortedMap<String, Object> queryResults = handleMultipleStatements(splitQueryStr, conn,
                        userPrefs, queryAttribute, session);
                logger.debug("keys : " + queryResults.keySet());
                model.addAttribute("sqlResultMap", queryResults);
                model.addAttribute("statementsExecuted", queryResults.size());

            }
        }
    } else {
        if (ServletFileUpload.isMultipartContent(request)) {
            logger.debug("is multipartcontent request");
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<?> fileItemsList = upload.parseRequest(request);

            logger.debug("fileItemList size = " + fileItemsList.size());
            Iterator<?> it = fileItemsList.iterator();
            while (it.hasNext()) {
                FileItem fileItemTemp = (FileItem) it.next();
                if (fileItemTemp.getFieldName().equals("sqlfilename")) {
                    QueryWindow qw = new QueryWindow();
                    qw.setQuery(fileItemTemp.getString());
                    model.addAttribute("queryAttribute", qw);
                    model.addAttribute("sqlfile", fileItemTemp.getName());
                }
            }
        }
    }

    return "query";
}

From source file:updatePledge.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:

    jComboBox3.removeAllItems();/*from  w  ww .  j av a  2 s  .  c o m*/
    jComboBox3.addItem("Item 1");

    jComboBox4.removeAllItems();
    jComboBox4.addItem("Item 1");

    String DonorID = jComboBox2.getSelectedItem().toString();

    try {
        try {
            Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(viewDonors.class.getName()).log(Level.SEVERE, null, ex);
        }
        Connection con;
        con = DriverManager.getConnection(DBcon.Connect(), DBcon.Login(), DBcon.Pass()); //(file path, db login, db password) - since it doesnt have a login, leave it blank

        Statement s = con.createStatement();
        System.out.println("Connection to DB established...");

        ResultSet rs = s.executeQuery("SELECT D.Amount, D.DonationID "
                + "FROM Donations as D INNER JOIN Pledges as P ON (D.DonationID = P.PledgeID) "
                + "WHERE (D.DonorID = '" + DonorID + "')");

        System.out.println("Is connection closed: " + con.isClosed());
        System.out.println("Connection to DB established...");
        while (rs.next()) {

            jComboBox3.addItem(rs.getString(1)); //Amount
            jComboBox4.addItem(rs.getString(2)); //DonationID

        }

        con.close();
        System.out.println("Is connection closed: " + con.isClosed());
    } catch (SQLException ex) {
        Logger.getLogger(userLogin.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(updatePledge.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.alibaba.druid.benckmark.pool.Oracle_Case4.java

private void p0(final DataSource dataSource, String name, int threadCount) throws Exception {

    final CountDownLatch startLatch = new CountDownLatch(1);
    final CountDownLatch endLatch = new CountDownLatch(threadCount);
    for (int i = 0; i < threadCount; ++i) {
        Thread thread = new Thread() {

            public void run() {
                try {
                    startLatch.await();/* ww  w  . j a  v  a 2 s.com*/

                    for (int i = 0; i < LOOP_COUNT; ++i) {
                        Connection conn = dataSource.getConnection();

                        int mod = i % 500;

                        String sql = SQL; // + " AND ROWNUM <= " + (mod + 1);
                        PreparedStatement stmt = conn.prepareStatement(sql);
                        stmt.setInt(1, 61);
                        ResultSet rs = stmt.executeQuery();
                        int rowCount = 0;
                        while (rs.next()) {
                            rowCount++;
                        }
                        // Assert.isTrue(!rs.isClosed());
                        rs.close();
                        // Assert.isTrue(!stmt.isClosed());
                        stmt.close();
                        Assert.isTrue(stmt.isClosed());
                        conn.close();
                        Assert.isTrue(conn.isClosed());
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                endLatch.countDown();
            }
        };
        thread.start();
    }
    long startMillis = System.currentTimeMillis();
    long startYGC = TestUtil.getYoungGC();
    long startFullGC = TestUtil.getFullGC();
    startLatch.countDown();
    endLatch.await();

    long millis = System.currentTimeMillis() - startMillis;
    long ygc = TestUtil.getYoungGC() - startYGC;
    long fullGC = TestUtil.getFullGC() - startFullGC;

    System.out.println("thread " + threadCount + " " + name + " millis : "
            + NumberFormat.getInstance().format(millis) + ", YGC " + ygc + " FGC " + fullGC);
}

From source file:com.tacitknowledge.util.migration.jdbc.JdbcMigrationLauncher.java

/**
 * Performs the application rollbacks/*from  w w w  .j av  a 2s.  co  m*/
 *
 * @param context       the database context to run the patches in
 * @param rollbackLevel the level the system should rollback to
 * @param forceRollback is a boolean indicating if the application should ignore a check to see if all patches are rollbackable
 * @return the number of patches applied
 * @throws SQLException       if an unrecoverable database error occurs while working with the patches table.
 * @throws MigrationException if an unrecoverable error occurs during the migration
 */
public int doRollbacks(JdbcMigrationContext context, int[] rollbackLevel, boolean forceRollback)
        throws SQLException, MigrationException {
    PatchInfoStore patchTable = createPatchStore(context);

    lockPatchStore(context);

    // Now apply the patches
    int executedPatchCount = 0;
    try {

        // remember the auto-commit state, and turn auto-commit off
        Connection conn = context.getConnection();
        boolean commitState = conn.getAutoCommit();
        conn.setAutoCommit(false);

        // run the rollbacks
        try {
            executedPatchCount = migrationProcess.doRollbacks(patchTable, rollbackLevel, context,
                    forceRollback);
        }

        // restore autocommit state
        finally {
            if ((conn != null) && !conn.isClosed()) {
                conn.setAutoCommit(commitState);
            }
        }
    } catch (MigrationException me) {
        // If there was any kind of error, we don't want to eat it, but we do
        // want to unlock the patch store. So do that, then re-throw.
        patchTable.unlockPatchStore();
        throw me;
    }

    // Do any post-patch tasks
    try {
        migrationProcess.doPostPatchMigrations(context);
        return executedPatchCount;
    } finally {
        try {
            patchTable.unlockPatchStore();
        } catch (MigrationException e) {
            log.error("Error unlocking patch table: ", e);
        }
    }
}

From source file:kr.co.bitnine.octopus.frame.SessionServerTest.java

@Test
public void testUser() throws Exception {
    Connection conn = getConnection("octopus", "bitnine");
    Statement stmt = conn.createStatement();
    stmt.execute("CREATE USER \"jsyang\" IDENTIFIED BY '0009'");
    stmt.close();//from   w  ww  . j  ava 2 s  .  c o  m
    conn.close();

    conn = getConnection("jsyang", "0009");
    assertFalse(conn.isClosed());
    conn.close();

    conn = getConnection("octopus", "bitnine");
    stmt = conn.createStatement();
    stmt.execute("ALTER USER \"jsyang\" IDENTIFIED BY 'jsyang' REPLACE '0009'");
    stmt.close();
    conn.close();

    conn = getConnection("jsyang", "jsyang");
    assertFalse(conn.isClosed());
    conn.close();

    conn = getConnection("octopus", "bitnine");
    stmt = conn.createStatement();
    stmt.execute("DROP USER \"jsyang\"");
    stmt.close();
    conn.close();
}