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.l2jfree.sql.L2DatabaseInstaller.java

private static double getDatabaseRevision() {
    double revision = -1;

    Connection con = null;/*from w w w  .  ja  v a2s . co m*/
    try {
        con = L2Database.getConnection();

        Statement st = con.createStatement();
        ResultSet rs = st.executeQuery("SELECT revision FROM _revision ORDER BY revision DESC LIMIT 1");

        if (rs.next())
            revision = rs.getDouble(1);

        rs.close();
        st.close();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        L2Database.close(con);
    }

    return revision;
}

From source file:at.becast.youploader.account.Account.java

public static boolean exists(String name) {
    Connection c = SQLite.getInstance();
    Statement stmt;
    try {/*from   ww  w.  ja v a 2  s . c o m*/
        stmt = c.createStatement();
        String sql = "SELECT * FROM `accounts` WHERE `name`='" + name + "'";
        ResultSet rs = stmt.executeQuery(sql);
        if (rs.isBeforeFirst()) {
            stmt.close();
            return true;
        } else {
            stmt.close();
            return false;
        }
    } catch (SQLException e) {
        LOG.error("Account exists error!", e);
        return false;
    }
}

From source file:com.nabla.wapp.server.database.Database.java

/**
 * Test if a table has any data//from   w ww.j a  va2s . c o  m
 * @param conn      - database connection
 * @param tableName   - table name
 * @return success
 * @throws SQLException
 */
public static boolean isTableEmpty(final Connection conn, final String tableName) throws SQLException {
    final Statement stmt = conn.createStatement();
    try {
        final ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM " + tableName + ";");
        try {
            return rs.next() && rs.getInt(1) == 0;
        } finally {
            rs.close();
        }
    } finally {
        stmt.close();
    }
}

From source file:com.krawler.database.DbPool.java

/**
 * Closes a statement and wraps any resulting exception in a
 * ServiceException./*from  w  w w  .  j ava  2  s  .c  o  m*/
 * 
 * @param stmt
 * @throws ServiceException
 */
public static void closeStatement(Statement stmt) throws ServiceException {
    if (stmt != null) {
        try {
            stmt.close();
        } catch (SQLException e) {
            throw ServiceException.FAILURE("closing statement", e);
        }
    }
}

From source file:net.geoprism.test.Sandbox.java

public static JSONArray getMapLayersBBox(List<Layer> layers) {

    JSONArray bboxArr = new JSONArray();
    ResultSet resultSet = null;/*from  w w w .  j av  a2  s  .  com*/
    String[] layerNames = null;

    // if (layers.size() > 0)
    if (layers.size() < 1) // for testing
    {
        layerNames = new String[layers.size()];
        String sql;

        // if (layers.size() == 1)
        if (layers.size() < 1) // for testing
        {
            // String layer = layers.get(0);
            // String viewName = layers.get;
            // layerNames[0] = layers.get(0);

            String viewName = "aa_test_data_view";

            sql = "SELECT ST_AsText(ST_Extent(" + viewName + "." + GeoserverFacade.GEOM_COLUMN
                    + ")) AS bbox FROM " + viewName;
        } else {
            // More than one layer so union the geometry columns
            sql = "SELECT ST_AsText(ST_Extent(geo_v)) AS bbox FROM (\n";

            for (int i = 0; i < layers.size(); i++) {
                Layer layer = layers.get(i);
                String viewName = layer.getName();
                layerNames[i] = layer.getName();

                sql += "(SELECT " + GeoserverFacade.GEOM_COLUMN + " AS geo_v FROM " + viewName + ") \n";

                if (i != layers.size() - 1) {
                    sql += "UNION \n";
                }
            }

            sql += ") bbox_union";
        }

        resultSet = Database.query(sql);
    }
    try {
        if (resultSet.next()) {

            String bbox = resultSet.getString("bbox");
            if (bbox != null) {
                Pattern p = Pattern.compile("POLYGON\\(\\((.*)\\)\\)");
                Matcher m = p.matcher(bbox);

                if (m.matches()) {
                    String coordinates = m.group(1);
                    List<Coordinate> coords = new LinkedList<Coordinate>();

                    for (String c : coordinates.split(",")) {
                        String[] xAndY = c.split(" ");
                        double x = Double.valueOf(xAndY[0]);
                        double y = Double.valueOf(xAndY[1]);

                        coords.add(new Coordinate(x, y));
                    }

                    Envelope e = new Envelope(coords.get(0), coords.get(2));

                    try {
                        bboxArr.put(e.getMinX());
                        bboxArr.put(e.getMinY());
                        bboxArr.put(e.getMaxX());
                        bboxArr.put(e.getMaxY());
                    } catch (JSONException ex) {
                        throw new ProgrammingErrorException(ex);
                    }
                } else {
                    // There will not be a match if there is a single point geo
                    // entity.
                    // In this case, return the x,y coordinates to OpenLayers.

                    p = Pattern.compile("POINT\\((.*)\\)");
                    m = p.matcher(bbox);
                    if (m.matches()) {
                        String c = m.group(1);
                        String[] xAndY = c.split(" ");
                        double x = Double.valueOf(xAndY[0]);
                        double y = Double.valueOf(xAndY[1]);

                        try {
                            bboxArr.put(x);
                            bboxArr.put(y);
                        } catch (JSONException ex) {
                            throw new ProgrammingErrorException(ex);
                        }
                    } else {
                        String error = "The database view(s) [" + StringUtils.join(layerNames, ",")
                                + "] could not be used to create a valid bounding box";
                        // throw new GeoServerReloadException(error);
                    }
                }
            }
        }

        return bboxArr;
    } catch (SQLException sqlEx1) {
        Database.throwDatabaseException(sqlEx1);
    } finally {
        try {
            java.sql.Statement statement = resultSet.getStatement();
            resultSet.close();
            statement.close();
        } catch (SQLException sqlEx2) {
            Database.throwDatabaseException(sqlEx2);
        }
    }

    // Some problem occured and the bbox couldn't be calculated.
    // Just return the African defaults
    try {
        bboxArr.put(36.718452);
        bboxArr.put(-17.700377000000003);
        bboxArr.put(36.938452);
        bboxArr.put(-17.480376999999997);
    } catch (JSONException ex) {
        throw new ProgrammingErrorException(ex);
    }

    return bboxArr;
}

From source file:chat.Models.java

/** @param test whether use the testing database */
public static AnnotationConfiguration build(boolean test) throws Exception {
    AnnotationConfiguration conf = new AnnotationConfiguration() {
        private static final long serialVersionUID = 1L;

        @Override/*from www  .j a v a2 s  .c o m*/
        public SessionFactory buildSessionFactory() throws HibernateException {
            if (!"org.hsqldb.jdbcDriver".equals(getProperty(Environment.DRIVER)))
                return super.buildSessionFactory();
            // fix the issue of hsqldb write delay stupid default value
            SessionFactory fac = super.buildSessionFactory();
            try {
                SessionImpl hib = (SessionImpl) fac.openSession();
                hib.beginTransaction();
                Statement stat = hib.getJDBCContext().borrowConnection().createStatement();
                stat.executeUpdate("SET WRITE_DELAY FALSE");
                hib.getTransaction().commit();
                stat.close();
                hib.close();
                LOG.info("SET WRITE_DELAY FALSE");
            } catch (Exception e) {
                throw new Error(e);
            }
            return fac;
        }
    };
    InputStreamReader connect = new InputStreamReader(
            Models.class.getResourceAsStream("/hibernate.connect.properties"), "UTF-8");
    conf.getProperties().load(connect);
    connect.close();

    conf.setNamingStrategy(new NamingStrategy() {
        @Override
        public String classToTableName(String entity) {
            return StringHelper.unqualify(entity);
        }

        @Override
        public String propertyToColumnName(String property) {
            return StringHelper.unqualify(property);
        }

        @Override
        public String tableName(String table) {
            return table;
        }

        @Override
        public String columnName(String column) {
            return column;
        }

        @Override
        public String collectionTableName(String ownerEntity, String ownerTable, String associatedEntity,
                String associatedTable, String property) {
            return ownerTable + "_" + StringHelper.unqualify(property);
        }

        @Override
        public String joinKeyColumnName(String joinedColumn, String joinedTable) {
            return joinedColumn;
        }

        @Override
        public String foreignKeyColumnName(String property, String propertyEntity, String propertyTable,
                String referencedColumn) {
            return property != null ? StringHelper.unqualify(property) : propertyTable;
        }

        @Override
        public String logicalColumnName(String column, String property) {
            return StringHelper.isEmpty(column) ? StringHelper.unqualify(property) : column;
        }

        @Override
        public String logicalCollectionTableName(String table, String ownerTable, String associatedTable,
                String property) {
            if (table != null)
                return table;
            return ownerTable + "_" + StringHelper.unqualify(property);
        }

        @Override
        public String logicalCollectionColumnName(String column, String property, String referencedColumn) {
            return StringHelper.isEmpty(column) ? property + "_" + referencedColumn : column;
        }
    });

    for (Class<?> c : Class2.packageClasses(Id.class))
        conf.addAnnotatedClass(c);

    if (!"false".equals(conf.getProperty(Environment.AUTOCOMMIT)))
        throw new RuntimeException(Environment.AUTOCOMMIT + " must be false");
    if (test)
        conf.setProperty(Environment.URL, conf.getProperty(Environment.URL + ".test"));
    return conf;
}

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

/**
 * Update a database, connected with c, with given request.
 * /*from w  w w.j a  v  a2 s . com*/
 * @param c
 * @param query
 * @throws SQLException
 */
public static void updateDatabaseQuery(Connection c, String query) throws SQLException {
    // Get a statement from the connection
    Statement stmt = c.createStatement();
    // Execute the query
    stmt.execute(query);
    // Close statement
    stmt.close();
}

From source file:com.nokia.helium.metadata.DerbyFactoryManagerCreator.java

/**
 * Checks the database integrity./* w  w w .  j a v a  2s .  com*/
 * @param urlPath - database path to be connected to.
 * @return boolean - true if db is valid false otherwise.
 */
private static boolean checkDatabaseIntegrity(File database) throws MetadataException {
    boolean result = false;
    Connection connection = null;
    try {
        connection = DriverManager.getConnection("jdbc:derby:" + database);
        if (connection != null) {
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("select version from version");
            int version = -1;
            if (rs.next()) {
                version = rs.getInt(1);
            }
            rs.close();
            stmt.close();
            connection.close();
            connection = null;
            result = version == Version.DB_VERSION;
        }
    } catch (SQLException ex) {
        try {
            DriverManager.getConnection("jdbc:derby:;shutdown=true");
        } catch (java.sql.SQLException sex) {
            // normal exception during database shutdown
            connection = null;
        }
        return false;
    } finally {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (java.sql.SQLException sex) {
            // normal exception during database shutdown
            connection = null;
        }
        connection = null;
        if (!result) {
            try {
                DriverManager.getConnection("jdbc:derby:;shutdown=true");
            } catch (java.sql.SQLException sex) {
                // normal exception during database shutdown
                connection = null;
            }
        }
    }
    //shutdown unloads the driver, driver need to be loaded again.
    return result;
}

From source file:desktop.olayinka.file.transfer.model.DerbyJDBCHelper.java

public static void cleanUp(Statement statement, ResultSet resultSet) {
    if (resultSet != null)
        try {//from w  w w  .j  av a  2 s  .co m
            resultSet.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    if (statement != null)
        try {
            statement.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
}

From source file:com.kylinolap.rest.service.BasicService.java

protected static void close(ResultSet resultSet, Statement stat, Connection conn) {
    OLAPContext.clearParameter();//from  www . ja  v  a  2  s .c  o m

    if (resultSet != null)
        try {
            resultSet.close();
        } catch (SQLException e) {
            logger.error("failed to close", e);
        }
    if (stat != null)
        try {
            stat.close();
        } catch (SQLException e) {
            logger.error("failed to close", e);
        }
    if (conn != null)
        try {
            conn.close();
        } catch (SQLException e) {
            logger.error("failed to close", e);
        }
}