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:org.bytesoft.openjtcc.supports.logger.DbTransactionLoggerImpl.java

public static void closeStatement(Statement stmt) {
    if (stmt != null) {
        try {//from w w  w.j  a  v a 2 s  .c o m
            stmt.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:net.antidot.sql.model.core.SQLConnector.java

/**
 * Drop all tables from database with connection c. Specific to MySQL
 * databases./*from   ww w  .  j  a  v  a  2  s.  c  o  m*/
 * 
 * @param c
 * @param driver 
 * @throws SQLException
 */
public static void resetMySQLDatabase(Connection c, DriverType driver) throws SQLException {
    // Get tables of database
    DatabaseMetaData meta = c.getMetaData();
    ResultSet tablesSet = meta.getTables(c.getCatalog(), null, "%", null);
    while (tablesSet.next()) {
        // Extract table name
        String tableName = new String(tablesSet.getString("TABLE_NAME"));
        String tableType = tablesSet.getString("TABLE_TYPE");
        // Get a statement from the connection
        Statement stmt = c.createStatement();
        // Execute the query
        if (driver == DriverType.MysqlDriver) {
            // MySQL compatibility
            stmt.execute("SET FOREIGN_KEY_CHECKS = 0");
            stmt.execute("DROP TABLE \"" + tableName + "\"");
        } else {
            if (tableType != null && tableType.equals("TABLE"))
                stmt.execute("DROP TABLE \"" + tableName + "\" CASCADE");
        }
        stmt.close();
    }
}

From source file:CheckJDBCInstallation_Oracle.java

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

From source file:net.sf.webphotos.tools.Thumbnail.java

/**
 * Abre uma conexo com o banco de dados atravs da classe BancoImagem,
 * busca um lote de imagens e faz thumbs para todas as fotos. No possui
 * utilizaes./*from  w  w  w.j  a va  2  s  .  c om*/
 */
public static void executaLote() {
    net.sf.webphotos.BancoImagem db = net.sf.webphotos.BancoImagem.getBancoImagem();

    try {
        db.configure("jdbc:mysql://localhost/test", "com.mysql.jdbc.Driver");
        BancoImagem.login();
        java.sql.Connection conn = BancoImagem.getConnection();
        java.sql.Statement st = conn.createStatement();
        java.sql.ResultSet rs = st.executeQuery("select * from fotos");

        int albumID, fotoID;
        String caminho;

        while (rs.next()) {
            albumID = rs.getInt("albumID");
            fotoID = rs.getInt("fotoID");
            caminho = "d:/bancoImagem/" + albumID + "/" + fotoID + ".jpg";
            makeThumbs(caminho);
            Util.out.println(caminho);
        }

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

    } catch (Exception e) {
        e.printStackTrace(Util.err);
    }
}

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

public static void assertRowCount(long expected, String tableName, Connection connection) {
    Statement stmt = null;
    ResultSet rs = null;//from   w  w  w. jav a  2  s .co m
    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.");
        }
    }
}

From source file:hnu.helper.DataBaseConnection.java

/**
 * Executes a SQL-String and returns true if everything went ok.
 * Can be used for DML and DDL. <br />Pete, do not use with SELECTs.
 *//*from w ww .  j  a va 2s.co m*/
public static boolean execute(String sql) {
    DataBaseConnection db = new DataBaseConnection();
    boolean returnValue = false;
    Connection conn = db.getDBConnection();
    Statement stmt = null;

    log.debug("About to execute: " + sql);
    try {
        stmt = conn.createStatement();
        stmt.executeUpdate(sql);
        log.debug(".. executed without exception (hope to return 'true') ");
        returnValue = true;
        //stmt.close();  - why do this here and in finally?
        //conn.close();
    } catch (SQLException ex) {
        log.error("Error executing: '" + sql + "'", ex);
    } finally {
        try {
            stmt.close();
        } catch (Exception ex) {
            log.error("Couldn't close the statement (so returning 'false').", ex);
            returnValue = false;
        } finally {
            // irrespective of whether closing the statement succeeds
            try {
                conn.close();
            } catch (SQLException ex) {
                log.error("Couldn't close the connection (so returning 'false').", ex);
                returnValue = false;
            }
        }
    }

    return returnValue;
}

From source file:com.autentia.tnt.version.Version.java

public static Version getDatabaseVersion(Connection con) throws SQLException {
    Statement stmt = null;
    ResultSet rs = null;/*w w  w  .  jav a2 s.c  o m*/
    String ret = null;

    try {
        stmt = con.createStatement();
        rs = stmt.executeQuery("select version from Version");

        if (rs.next()) {
            ret = rs.getString("version");
        }
    } catch (SQLException e) {
        throw e;
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                log.error("Error al liberar el resultset", e);
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                log.error("Error al liberar el statement", e);
            }
        }
    }

    return new Version(ret == null ? "0" : ret);
}

From source file:com.tfm.utad.sqoopdata.SqoopVerticaDB.java

private static Long findMaxID(Connection conn) {
    Long id = (long) 0;
    Statement stmt = null;
    String query;/*from ww w.j  av  a 2 s  . com*/
    try {
        stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        query = "SELECT MAX(id) AS id FROM s1.coordinates";
        LOG.info("Query execution: " + query);
        ResultSet rs = stmt.executeQuery(query);
        while (rs.next()) {
            id = (long) rs.getInt("id");
        }
    } catch (SQLException e) {
        LOG.error("SQLException error: " + e.toString());
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ex) {
                LOG.error("Statement error: " + ex.toString());
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ex) {
                LOG.error("Connection error: " + ex.toString());
            }
        }
    }
    return id;
}

From source file:com.trackplus.ddl.DataWriter.java

private static void executeUpdate(Connection con, Statement stmt, String s) throws DDLException {
    try {/*w  w w  . j  av a 2  s  . c om*/
        stmt.executeUpdate(s);
    } catch (SQLException e) {
        LOGGER.error("Error execute script line:" + e.getMessage());
        LOGGER.warn("-------------\n\n");
        LOGGER.warn(s);
        LOGGER.warn("-------------\n\n");
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
        try {
            stmt.close();
            con.rollback();
            con.setAutoCommit(true);
        } catch (SQLException ex) {
            throw new DDLException(e.getMessage(), e);
        }
        throw new DDLException(e.getMessage(), e);
    }
}

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;/*w w w .  j av  a 2  s .c o m*/
    Statement stmt = conn.createStatement();
    try {
        //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();
        }
    }
}