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:com.baidu.qa.service.test.util.JdbcUtil.java

protected static void excuteVerifyDeleteSqls(List<String> sqlStrs, String dbname) throws Exception {

    Connection con = null;//w  ww.  java2  s  .com
    Statement sm = null;
    ResultSet rs = null;
    try {
        //?
        con = MysqlDatabaseManager.getCon(dbname);
        Assert.assertNotNull("connect to db error:" + dbname, con);

        //??
        sm = con.createStatement();
        for (String sqlStr : sqlStrs) {
            rs = sm.executeQuery(sqlStr);
            log.info("[sql:]" + sqlStr);

            Assert.assertFalse("[db expect error],has data like:" + sqlStr, rs.next());
            rs.close();
        }

    } catch (Exception e) {

        throw e;
    } finally {
        if (con != null) {
            con.close();
        }
        if (sm != null) {
            sm.close();
        }
        if (rs != null) {
            rs.close();
        }
    }

}

From source file:com.baidu.qa.service.test.util.JdbcUtil.java

protected static void excuteVerifySqls(List<String> sqlStrs, String dbname) throws Exception {

    //   ???// ww w .j av a 2 s. c  o  m
    Connection con = null;
    Statement sm = null;
    ResultSet rs = null;
    try {
        //?
        con = MysqlDatabaseManager.getCon(dbname);
        Assert.assertNotNull("connect to db error:" + dbname, con);

        //??
        sm = con.createStatement();
        for (String sqlStr : sqlStrs) {
            rs = sm.executeQuery(sqlStr);
            log.info("[sql:]" + sqlStr);

            Assert.assertTrue("[db expect error],has no data like:" + sqlStr, rs.next());
            rs.close();
        }

    } catch (Exception e) {
        throw e;
    } finally {
        if (con != null) {
            con.close();
        }
        if (sm != null) {
            sm.close();
        }
        if (rs != null) {
            rs.close();
        }

    }

}

From source file:org.bytesoft.openjtcc.supports.logger.DbTransactionLoggerImpl.java

public static void closeResultSet(ResultSet rs) {
    if (rs != null) {
        try {//from  w w w.  jav  a2 s.  c  o m
            rs.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.nabla.dc.server.handler.fixed_asset.Asset.java

static public <P> boolean validateDepreciationPeriod(final Connection conn, final IAssetRecord asset,
        @Nullable final P pos, final IErrorList<P> errors) throws SQLException, DispatchException {
    final PreparedStatement stmt = StatementFormat.prepare(conn,
            "SELECT t.min_depreciation_period, t.max_depreciation_period"
                    + " FROM fa_asset_category AS t INNER JOIN fa_company_asset_category AS r ON r.fa_asset_category_id=t.id"
                    + " WHERE r.id=?;",
            asset.getCompanyAssetCategoryId());
    try {/*w  ww .  j a  v  a  2 s .c  om*/
        final ResultSet rs = stmt.executeQuery();
        try {
            if (!rs.next()) {
                errors.add(pos, asset.getCategoryField(), ServerErrors.UNDEFINED_ASSET_CATEGORY_FOR_COMPANY);
                return false;
            }
            if (rs.getInt("min_depreciation_period") > asset.getDepreciationPeriod()
                    || rs.getInt("max_depreciation_period") < asset.getDepreciationPeriod()) {
                errors.add(pos, asset.getDepreciationPeriodField(), CommonServerErrors.INVALID_VALUE);
                return false;
            }
        } finally {
            rs.close();
        }
    } finally {
        stmt.close();
    }
    return true;
}

From source file:com.jaspersoft.jasperserver.api.engine.common.virtualdatasourcequery.VirtualSQLDataSource.java

public static Set<String> discoverSchemas(Connection conn) throws SQLException {
    DatabaseMetaData dbMetaData = conn.getMetaData();
    ResultSet rs = null;
    try {// w  w  w  . j a  v  a2s  .co m
        Set<String> set = new LinkedHashSet<String>();
        rs = dbMetaData.getSchemas();
        while (rs.next()) {
            String schema = rs.getString(TABLE_SCHEM);
            if (schema != null)
                set.add(schema);
        }
        return set;
    } catch (SQLException ex) {
        log.error("Cannot get schemas", ex);
        throw ex;
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:edu.lafayette.metadb.model.userman.UserManDAO.java

/**
 * Get a list of all the users in the system.
 * @return an Arraylist of Users representing all the users in the system.
 *///from   ww w .  j a  va  2 s  . c  o  m
public static ArrayList<User> getUserList() {
    ArrayList<User> list = new ArrayList<User>();

    Connection conn = Conn.initialize(); // Establish connection
    if (conn != null) {
        try {
            PreparedStatement getUserList = conn.prepareStatement(GET_USER_LIST);
            ResultSet userData = getUserList.executeQuery();

            while (userData.next()) {
                String username = userData.getString(Global.USER_NAME);
                list.add(getUserData(username));
            }
            userData.close();

            getUserList.close();
            conn.close();
        } catch (Exception e) {
            MetaDbHelper.logEvent(e);
        }
    }
    return list;
}

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

private static long countRecords(String jdbcUrl, HoodieTableMetaClient source, String srcDb,
        String startDateStr, String endDateStr, String user, String pass) throws SQLException {
    Connection conn = HiveUtil.getConnection(jdbcUrl, user, pass);
    ResultSet rs = null;
    Statement stmt = conn.createStatement();
    try {//from  w w w . j  av a2s .  c  o 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 " + srcDb + "."
                + source.getTableConfig().getTableName() + " where datestr>'" + startDateStr
                + "' and datestr<='" + endDateStr + "'");
        if (rs.next()) {
            return rs.getLong("cnt");
        }
        return -1;
    } finally {
        if (rs != null) {
            rs.close();
        }
        if (stmt != null) {
            stmt.close();
        }
    }
}

From source file:CheckJDBCInstallation_Oracle.java

/**
 * Test Validity of a Connection//from w  w  w . j  a va2s.  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) {
        return false;
    } finally {
        // close database resources
        try {
            rs.close();
            stmt.close();
        } catch (Exception e) {
            // ignore
        }
    }
}

From source file:database.HashTablesTools.java

public static void createTablesIfTheyDontExists(Connection connection, String tableSequenceName,
        String tableFailureName) {

    ResultSet resultTables = null;
    try {//from w  w w .j a  va 2 s. c  o  m

        /**
         DatabaseMetaData dmd = connection.getMetaData();
         ResultSet rs = dmd.getSchemas();
         List<String> schemas = new ArrayList<String>();
         while (rs.next()) {
         schemas.add(rs.getString("TABLE_SCHEM"));
         }
         rs.close();
         System.out.println("Schemas : ");
         for (String schema : schemas) {
         System.out.println(schema);
         }
         */
        // get database metadata
        DatabaseMetaData metaData = connection.getMetaData();
        ResultSet rsSchema = metaData.getTables(null, "ME", "%", null);
        List<String> tables = new ArrayList<String>();
        while (rsSchema.next()) {
            tables.add(rsSchema.getString(3)); // 3: table name
        }
        rsSchema.close();

        if (!tables.contains(tableSequenceName.toUpperCase())) {
            System.out.println(tableSequenceName + " dont exist");
            createTables(connection, tableSequenceName, tableFailureName);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

}

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

private static boolean hasTables(Connection conn) {
    boolean hasTables = false;
    try {/*from ww w.jav a 2  s  .  c om*/
        DatabaseMetaData md = conn.getMetaData();
        String userName = md.getUserName();
        String url = md.getURL();
        boolean isOracleOrDb2 = url.startsWith("jdbc:oracle") || url.startsWith("jdbc:db2");
        ResultSet rsTables = md.getTables(conn.getCatalog(), isOracleOrDb2 ? userName : null, null, null);
        LOGGER.info("Getting the tables metadata");
        if (rsTables != null && rsTables.next()) {
            LOGGER.info("Find TSITE table...");

            while (rsTables.next()) {
                String tableName = rsTables.getString("TABLE_NAME");
                String tablenameUpperCase = tableName.toUpperCase();
                if ("TSITE".equals(tablenameUpperCase)) {
                    LOGGER.info("TSITE table found");
                    hasTables = true;
                    break;
                } else {
                    if (tablenameUpperCase.endsWith("TSITE")) {
                        LOGGER.info(tablenameUpperCase + " table found");
                        hasTables = true;
                        break;
                    }
                }
            }
        }
    } catch (Exception e) {
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    if (!hasTables) {
        Statement stmt = null;
        ResultSet rs = null;
        try {
            stmt = conn.createStatement();
            rs = stmt.executeQuery("SELECT OBJECTID FROM TSITE");
            if (rs.next()) {
                hasTables = true;
            }
        } catch (SQLException e) {
            LOGGER.info("Table TSITE  does not exist");
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                }
            }
        }
    }
    return hasTables;
}