Example usage for java.sql ResultSet close

List of usage examples for java.sql ResultSet close

Introduction

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

Prototype

void close() throws SQLException;

Source Link

Document

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

Usage

From source file:es.tena.foundation.util.POIUtil.java

public static void generateXLS(String tabla, String filename, Connection conn, String encoding)
        throws SQLException {
    String query = "";
    try {/*  w w w.  j  av  a 2 s.  c om*/
        query = "SELECT * FROM (" + tabla + ")";
        PreparedStatement stmt = conn.prepareStatement(query);
        ResultSet rset = stmt.executeQuery();

        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet sheet = wb.createSheet(filename);
        String sheetRef = sheet.getPackagePart().getPartName().getName();
        String template = "c:\\temp\\template_" + filename + ".xlsx";
        FileOutputStream os = new FileOutputStream(template);
        wb.write(os);
        os.close();

        File tmp = File.createTempFile("sheet", ".xml");
        Writer fw = new OutputStreamWriter(new FileOutputStream(tmp), encoding);
        generate(fw, rset, encoding);
        rset.close();
        stmt.close();
        fw.close();

        FileOutputStream out = new FileOutputStream(
                "c:\\temp\\" + filename + sdf.format(calendario.getTime()) + ".xlsx");
        FileUtil.substitute(new File(template), tmp, sheetRef.substring(1), out);
        out.close();
        Logger.getLogger(POIUtil.class.getName()).log(Level.INFO, "Creado con exito {0}", filename);
    } catch (Exception ex) {
        ex.printStackTrace();
        Logger.getLogger(POIUtil.class.getName()).log(Level.SEVERE, null, query + "\n" + ex);
        System.out.println(query);
    } finally {
        conn.close();
    }
}

From source file:ProxyAuthTest.java

private static void runQuery(String sqlStmt) throws Exception {
    Statement stmt = con.createStatement();
    ResultSet res = stmt.executeQuery(sqlStmt);

    ResultSetMetaData meta = res.getMetaData();
    System.out.println("Resultset has " + meta.getColumnCount() + " columns");
    for (int i = 1; i <= meta.getColumnCount(); i++) {
        System.out.println(/*  w  ww .  j ava2 s.c  o m*/
                "Column #" + i + " Name: " + meta.getColumnName(i) + " Type: " + meta.getColumnType(i));
    }

    while (res.next()) {
        for (int i = 1; i <= meta.getColumnCount(); i++) {
            System.out.println("Column #" + i + ": " + res.getString(i));
        }
    }
    res.close();
    stmt.close();
}

From source file:com.toxind.benchmark.thrid.ibatis.sqlmap.engine.execution.SqlExecutor.java

/**
 * @param rs/*from w  ww .j  a  v  a 2  s. c  o m*/
 */
private static void closeResultSet(ResultSet rs) {
    if (rs != null) {
        try {
            rs.close();
        } catch (SQLException e) {
            // ignore
        }
    }
}

From source file:com.chaosinmotion.securechat.server.commands.UpdateForgottenPassword.java

public static boolean processRequest(Login.UserInfo userinfo, JSONObject requestParams)
        throws ClassNotFoundException, SQLException, IOException {
    String newPassword = requestParams.getString("password");
    String requestToken = requestParams.getString("token");

    /*/*from  w  ww  .j  a  v a  2s.  co  m*/
     * Determine if the token matches for this user record. We are in the
     * unique situation of having a logged in user, but he doesn't know
     * his password. We also ignore any requests with an expired
     * token.
     */

    Connection c = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        /*
         * Delete old requests
         */
        c = Database.get();
        ps = c.prepareStatement("DELETE FROM forgotpassword WHERE expires < LOCALTIMESTAMP");
        ps.execute();

        ps.close();
        ps = null;

        /*
         * Verify the token we passed back was correct
         */
        ps = c.prepareStatement(
                "SELECT token " + "FROM forgotpassword " + "WHERE userid = ? " + "AND token = ?");
        ps.setInt(1, userinfo.getUserID());
        ps.setString(2, requestToken);
        rs = ps.executeQuery();
        if (!rs.next())
            return false; // token does not exist or expired.

        rs.close();
        rs = null;
        ps.close();
        ps = null;

        /*
         * Step 2: Modify the password.
         */

        ps = c.prepareStatement("UPDATE Users SET password = ? WHERE userid = ?");
        ps.setString(1, newPassword);
        ps.setInt(2, userinfo.getUserID());
        ps.execute();

        return true;
    } finally {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
        if (c != null)
            c.close();
    }
}

From source file:CheckJDBCInstallation.java

/**
 * Test Validity of a Connection// w w  w . j  a v  a 2  s.c  om
 * 
 * @param conn
 *          a JDBC connection object
 * @param query
 *          a sql query to test against db connection
 * @return true if a given connection object is a valid one; otherwise return
 *         false.
 */
public static boolean testConnection(Connection conn, String query) {
    ResultSet rs = null;
    Statement stmt = null;
    try {
        stmt = conn.createStatement();
        if (stmt == null) {
            return false;
        }

        rs = stmt.executeQuery(query);
        if (rs == null) {
            return false;
        }

        // connection object is valid: you were able to
        // connect to the database and return something useful.
        if (rs.next()) {
            return true;
        }

        // there is no hope any more for the validity
        // of the Connection object
        return false;
    } catch (Exception e) {
        // something went wrong: connection is bad
        return false;
    } finally {
        // close database resources
        try {
            rs.close();
            stmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.uber.hoodie.cli.utils.HiveUtil.java

public static long countRecords(String jdbcUrl, HoodieTableMetaClient source, String dbName, String user,
        String pass) throws SQLException {
    Connection conn = HiveUtil.getConnection(jdbcUrl, user, pass);
    ResultSet rs = null;
    Statement stmt = conn.createStatement();
    try {//w w w .j  a  v a 2 s .co m
        //stmt.execute("set mapred.job.queue.name=<queue_name>");
        stmt.execute("set hive.input.format=org.apache.hadoop.hive.ql.io.HiveInputFormat");
        stmt.execute("set hive.stats.autogather=false");
        rs = stmt.executeQuery("select count(`_hoodie_commit_time`) as cnt from " + dbName + "."
                + source.getTableConfig().getTableName());
        long count = -1;
        if (rs.next()) {
            count = rs.getLong("cnt");
        }
        System.out.println("Total records in " + source.getTableConfig().getTableName() + " is " + count);
        return count;
    } finally {
        if (rs != null) {
            rs.close();
        }
        if (stmt != null) {
            stmt.close();
        }
    }
}

From source file:CheckJDBCInstallation_MySQL.java

/**
 * Test Validity of a Connection/*from  ww w .j  av  a2 s.  c o  m*/
 * 
 * @param conn
 *          a JDBC connection object
 * @param query
 *          a sql query to test against database connection
 * @return true if a given connection object is a valid one; otherwise return
 *         false.
 */
public static boolean testConnection(Connection conn, String query) {

    ResultSet rs = null;
    Statement stmt = null;
    try {
        stmt = conn.createStatement();
        if (stmt == null) {
            return false;
        }

        rs = stmt.executeQuery(query);
        if (rs == null) {
            return false;
        }

        if (rs.next()) {
            // connection object is valid: we were able to
            // connect to the database and return something useful.
            return true;
        }

        // there is no hope any more for the validity
        // of the connection object
        return false;

    } catch (Exception e) {
        //
        // something went wrong: connection is bad
        //
        return false;
    } finally {
        try {
            rs.close();
            stmt.close();
            conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:gridool.db.helpers.GridDbUtils.java

@Nullable
public static PrimaryKey getPrimaryKey(@Nonnull final Connection conn, @CheckForNull final String pkTableName,
        final boolean reserveAdditionalInfo) throws SQLException {
    if (pkTableName == null) {
        throw new IllegalArgumentException();
    }//from  ww  w .  j a  v a 2 s . co  m
    DatabaseMetaData metadata = conn.getMetaData();
    String catalog = conn.getCatalog();
    final ResultSet rs = metadata.getPrimaryKeys(catalog, null, pkTableName);
    final PrimaryKey pkey;
    try {
        if (!rs.next()) {
            return null;
        }
        String pkName = rs.getString("PK_NAME");
        pkey = new PrimaryKey(pkName, pkTableName);
        do {
            pkey.addColumn(rs);
        } while (rs.next());
    } finally {
        rs.close();
    }

    if (reserveAdditionalInfo) {
        // set foreign key column positions
        pkey.setColumnPositions(metadata);
        // set exported keys
        final Collection<ForeignKey> exportedKeys = getExportedKeys(conn, pkTableName, false);
        if (!exportedKeys.isEmpty()) {
            final List<String> pkColumnsProbe = pkey.getColumnNames();
            final int numPkColumnsProbe = pkColumnsProbe.size();
            final List<ForeignKey> exportedKeyList = new ArrayList<ForeignKey>(4);
            outer: for (ForeignKey fk : exportedKeys) {
                List<String> names = fk.getPkColumnNames();
                if (names.size() != numPkColumnsProbe) {
                    continue;
                }
                for (String name : names) {
                    if (!pkColumnsProbe.contains(name)) {
                        continue outer;
                    }
                }
                exportedKeyList.add(fk);
            }
            if (!exportedKeyList.isEmpty()) {
                pkey.setExportedKeys(exportedKeyList);
            }
        }
    }
    return pkey;
}

From source file:com.aurel.track.dbase.UpdateDbSchema.java

/**
 * Gets the database version/* w  ww  .j ava 2  s . c  o  m*/
 * @param dbConnection
 * @return
 */
public static int getDBVersion(Connection dbConnection) {
    Statement istmt = null;
    ResultSet rs = null;
    try {
        istmt = dbConnection.createStatement();
        rs = istmt.executeQuery("SELECT DBVERSION FROM TSITE");
        if (rs == null || !rs.next()) {
            LOGGER.info("TSITE is empty.");
        } else {
            return rs.getInt(1);
        }
    } catch (Exception e) {
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    } finally {
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (Exception e) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
        try {
            if (istmt != null) {
                istmt.close();
            }
        } catch (Exception e) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
        try {
            if (dbConnection != null) {
                dbConnection.close();
            }
        } catch (Exception e) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
    return 0;
}

From source file:com.cloudera.sqoop.manager.PostgresqlExportTest.java

public static void assertRowCount(long expected, String tableName, Connection connection) {
    Statement stmt = null;//from www. jav a  2s  .  co m
    ResultSet rs = null;
    try {
        stmt = connection.createStatement();
        rs = stmt.executeQuery("SELECT count(*) FROM " + tableName);

        rs.next();

        assertEquals(expected, rs.getLong(1));
    } catch (SQLException e) {
        LOG.error("Can't verify number of rows", e);
        fail();
    } finally {
        try {
            connection.commit();

            if (stmt != null) {
                stmt.close();
            }
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException ex) {
            LOG.info("Ignored exception in finally block.");
        }
    }
}