Example usage for java.sql Statement close

List of usage examples for java.sql Statement close

Introduction

In this page you can find the example usage for java.sql Statement close.

Prototype

void close() throws SQLException;

Source Link

Document

Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed.

Usage

From source file:com.thoughtworks.go.server.database.DatabaseFixture.java

public static Object[][] query(String query, H2Database h2Database) {
    BasicDataSource source = h2Database.createDataSource();
    Connection con = null;//from   www.j  av a2  s .c  o  m
    Statement stmt = null;
    ResultSet rs = null;
    try {
        con = source.getConnection();
        stmt = con.createStatement();
        rs = stmt.executeQuery(query);
        int columnCount = rs.getMetaData().getColumnCount();
        List<Object[]> objects = new ArrayList<>();
        while (rs.next()) {
            Object[] values = new Object[columnCount];
            for (int i = 0; i < values.length; i++) {
                values[i] = rs.getObject(i + 1);
            }
            objects.add(values);
        }
        return objects.toArray(new Object[0][0]);
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            assert stmt != null;
            stmt.close();
            con.close();
            assert rs != null;
            rs.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.flexive.core.Database.java

/**
 * Helper function to close connections and statements.
 * A FxDbException is thrown if the close of the connection failed.
 * No Exception is thrown if the Statement failed to close, but a error is logged.
 *
 * @param caller a string representing the calling function/module, or null
 * @param con    the connection to close, or null
 * @param stmt   the statement to close, or null
 *///from   ww w  .jav a  2 s.  co  m
public static void closeObjects(String caller, Connection con, Statement stmt) {
    try {
        if (stmt != null)
            stmt.close();
    } catch (Exception exc) {
        //noinspection ThrowableInstanceNeverThrown
        StackTraceElement[] se = new Throwable().getStackTrace();
        LOG.error(((caller != null) ? caller + " f" : "F") + "ailed to close the statement(s): "
                + exc.getMessage() + " Calling line: " + se[2].toString());
    }
    if (con != null) {
        try {
            if (!con.isClosed()) {
                con.close();
            }
        } catch (SQLException exc) {
            //noinspection ThrowableInstanceNeverThrown
            FxDbException dbExc = new FxDbException(
                    ((caller != null) ? caller + " is u" : "U") + "nable to close the db connection");
            LOG.error(dbExc);
            System.err.println(dbExc.getMessage());
        }
    }
}

From source file:com.stratelia.webactiv.util.DBUtil.java

public static void close(ResultSet rs, Statement st) {
    if (rs != null) {
        try {//from   w w  w.java  2  s .  co  m
            rs.close();
        } catch (SQLException e) {
            SilverTrace.error("util", "DBUtil.close", "util.CAN_T_CLOSE_RESULTSET", e);
        }
    }
    if (st != null) {
        try {
            st.close();
        } catch (SQLException e) {
            SilverTrace.error("util", "DBUtil.close", "util.CAN_T_CLOSE_STATEMENT", e);
        }
    }
}

From source file:com.flexive.core.Database.java

/**
 * Helper function to close connections and statements.
 * No Exception is thrown if the Statement failed to close, but a error is logged.
 *
 * @param caller a string representing the calling function/module, or null
 * @param stmts   the statements to close, or null
 *///from   w  ww .  j  a  v a  2  s.  co  m
public static void closeObjects(String caller, Statement... stmts) {
    for (Statement stmt : stmts) {
        try {
            if (stmt != null)
                stmt.close();
        } catch (Exception exc) {
            //noinspection ThrowableInstanceNeverThrown
            StackTraceElement[] se = new Throwable().getStackTrace();
            LOG.error(((caller != null) ? caller + " f" : "F") + "ailed to close the statement(s): "
                    + exc.getMessage() + " Calling line: " + se[2].toString());
        }
    }
}

From source file:jfutbol.com.jfutbol.GcmSender.java

public static void updateNotificationAsSent(int userId) {
    Connection conn = null;/* w ww.ja va2  s .  com*/
    Statement stmt = null;

    try {
        // STEP 2: Register JDBC driver
        Class.forName(JDBC_DRIVER);
        // STEP 3: Open a connection
        System.out.println("Connecting to database...");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);
        // STEP 4: Execute a query
        System.out.println("Creating statement...");
        stmt = conn.createStatement();
        String sql;
        sql = "UPDATE notifications SET sentByGCM=1 WHERE userId=" + userId;
        int rs = stmt.executeUpdate(sql);
        // STEP 5: Extract data from result set
        if (rs > 0) {
            // System.out.print("Notifications sent to userId: "+userId);
        }
        // STEP 6: Clean-up environment
        stmt.close();
        conn.close();
    } catch (SQLException se) {
        // Handle errors for JDBC
        log.error(se.getMessage());
        se.printStackTrace();
    } catch (Exception e) {
        // Handle errors for Class.forName
        log.error(e.getMessage());
        e.printStackTrace();
    } finally {
        // finally block used to close resources
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException se2) {
            log.error(se2.getMessage());
        } // nothing we can do
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException se) {
            log.error(se.getMessage());
            se.printStackTrace();
        } // end finally try
    } // end try
}

From source file:com.srotya.tau.api.Utils.java

public static void createDatabase(String dbConnectionString, String dbName, String user, String pass,
        String driver) throws Exception {
    Connection conn = null;//from  ww w. ja  va2s .c  o m
    Statement stmt = null;
    try {
        // STEP 2: Register JDBC driver
        Class.forName(driver);

        // STEP 3: Open a connection
        System.out.println("Connecting to database with connection string:" + dbConnectionString);
        conn = DriverManager.getConnection(dbConnectionString, user, pass);

        // STEP 4: Execute a query
        System.out.println("Creating database...");
        stmt = conn.createStatement();

        String sql = "CREATE DATABASE IF NOT EXISTS " + dbName;
        stmt.executeUpdate(sql);
        System.out.println("Database created successfully...");
    } finally {
        // finally block used to close resources
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException se2) {
        } // nothing we can do
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException se) {
            se.printStackTrace();
        } // end finally try
    } // end try
}

From source file:com.oracle.tutorial.jdbc.SuppliersTable.java

public static void viewTable(Connection con) throws SQLException {
    Statement stmt = null;
    String query = "select SUP_ID, SUP_NAME, STREET, CITY, STATE, ZIP from SUPPLIERS";
    try {//from  w  ww  .ja  v  a2s.co m
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        while (rs.next()) {
            int supplierID = rs.getInt("SUP_ID");
            String supplierName = rs.getString("SUP_NAME");
            String street = rs.getString("STREET");
            String city = rs.getString("CITY");
            String state = rs.getString("STATE");
            String zip = rs.getString("ZIP");
            System.out.println(
                    supplierName + "(" + supplierID + "): " + street + ", " + city + ", " + state + ", " + zip);
        }
    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    } finally {
        if (stmt != null) {
            stmt.close();
        }
    }
}

From source file:dk.netarkivet.common.utils.DBUtils.java

/**
 * Close a statement, if not closed already
 * Note: This does not throw any a SQLException, because
 * it is always called inside a finally-clause.
 * Exceptions are logged as warnings, though.
 * @param s a statement/* www  . j  a v  a  2s .c  o m*/
 */
public static void closeStatementIfOpen(Statement s) {
    if (s != null) {
        try {
            s.close();
        } catch (SQLException e) {
            log.warn("Error closing SQL statement " + s + "\n" + ExceptionUtils.getSQLExceptionCause(e), e);
        }
    }
}

From source file:au.org.ala.layers.stats.ObjectsStatsGenerator.java

private static void updateArea(String fid) {

    try {/* w w  w  .ja va2 s. co  m*/
        Connection conn = getConnection();
        String sql = "SELECT pid from objects where area_km is null and st_geometrytype(the_geom) <> 'Point'";
        if (fid != null) {
            sql = sql + " and fid = '" + fid + "'";
        }

        sql = sql + " limit 200000;";

        System.out.println("loading area_km ...");
        Statement s1 = conn.createStatement();
        ResultSet rs1 = s1.executeQuery(sql);

        LinkedBlockingQueue<String> data = new LinkedBlockingQueue<String>();
        while (rs1.next()) {
            data.put(rs1.getString("pid"));
        }

        CountDownLatch cdl = new CountDownLatch(data.size());

        AreaThread[] threads = new AreaThread[CONCURRENT_THREADS];
        for (int j = 0; j < CONCURRENT_THREADS; j++) {
            threads[j] = new AreaThread(data, cdl, getConnection().createStatement());
            threads[j].start();
        }

        cdl.await();

        for (int j = 0; j < CONCURRENT_THREADS; j++) {
            threads[j].s.close();
            threads[j].interrupt();
        }
        rs1.close();
        s1.close();
        conn.close();
        return;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return;
}

From source file:ece356.UserDBAO.java

public static Connection getConnection() throws ClassNotFoundException, SQLException, NamingException {
    InitialContext cxt = new InitialContext();
    if (cxt == null) {
        throw new RuntimeException("Unable to create naming context!");
    }//from w  ww . j  av a2  s. co m
    Context dbContext = (Context) cxt.lookup("java:comp/env");
    DataSource ds = (DataSource) dbContext.lookup("jdbc/myDatasource");
    if (ds == null) {
        throw new RuntimeException("Data source not found!");
    }
    Connection con = ds.getConnection();

    /*Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection(url, user, pwd);*/
    Statement stmt = null;
    try {
        con.createStatement();
        stmt = con.createStatement();
        stmt.execute("USE ece356db_" + nid);
    } finally {
        if (stmt != null) {
            stmt.close();
        }
    }
    return con;
}