Example usage for java.sql Statement execute

List of usage examples for java.sql Statement execute

Introduction

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

Prototype

boolean execute(String sql) throws SQLException;

Source Link

Document

Executes the given SQL statement, which may return multiple results.

Usage

From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java

private boolean isDatabaseRunning() {
    Statement statement = null;
    Connection connection = null;
    SqlConfig.getSqlSessionManager().startManagedSession();

    try {/*from w ww  .j a  va2  s. c o m*/
        connection = SqlConfig.getSqlSessionManager().getConnection();
        statement = connection.createStatement();
        statement.execute("SELECT 1 FROM CHANNEL");
        return true;
    } catch (Exception e) {
        logger.warn("could not retrieve status of database", e);
        return false;
    } finally {
        DbUtils.closeQuietly(statement);
        DbUtils.closeQuietly(connection);
        if (SqlConfig.getSqlSessionManager().isManagedSessionStarted()) {
            SqlConfig.getSqlSessionManager().close();
        }
    }
}

From source file:de.uniwue.info6.database.jdbc.ConnectionManager.java

/**
 *
 *
 * @param connection/*from   w  ww.  j  a  v  a 2 s  .  com*/
 * @param dbName
 */
public void createDatabase(final Connection connection, final String dbName) {
    String createStatement = "CREATE DATABASE IF NOT EXISTS `" + dbName + "`";
    Statement statement = null;
    try {
        if (connection != null) {
            statement = connection.createStatement();
            statement.execute(createStatement);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:kr.co.bitnine.octopus.frame.SessionServerTest.java

@Test
public void testUpdateDataSource1() throws Exception {
    Connection conn = getConnection("octopus", "bitnine");
    Statement stmt = conn.createStatement();

    final String tblName = "TMP";
    dataMemDb.runExecuteUpdate("CREATE TABLE \"" + tblName + "\" (\"ID\" INTEGER, \"NAME\" STRING)");
    dataMemDb.runExecuteUpdate("INSERT INTO \"" + tblName + "\" VALUES (1, 'yjchoi')");

    boolean exceptionCaught = false;
    try {//from   w  ww.ja v a 2 s  . c o  m
        checkNumRows(stmt, tblName);
    } catch (SQLException e) {
        exceptionCaught = true;
    }
    assertTrue(exceptionCaught);

    int rows = checkNumRows(stmt, "employee");
    assertEquals(rows, 10);

    DatabaseMetaData metaData = conn.getMetaData();
    ResultSet rs = metaData.getTables(dataMemDb.name, "%DEFAULT", "%", null);
    while (rs.next())
        System.out.println(" *** " + rs.getString("TABLE_NAME"));

    stmt.execute("ALTER SYSTEM UPDATE DATASOURCE \"" + dataMemDb.name + '"');

    metaData = conn.getMetaData();
    rs = metaData.getTables(dataMemDb.name, "%DEFAULT", "%", null);
    while (rs.next())
        System.out.println(" *** " + rs.getString("TABLE_NAME"));

    rows = checkNumRows(stmt, tblName);
    assertEquals(rows, 1);

    stmt.close();
    conn.close();
}

From source file:com.glaf.core.util.DBUtils.java

public static String createTable(TableDefinition classDefinition) {
    Connection connection = null;
    Statement statement = null;
    try {//  w  w  w. j  a v a 2  s  . c om
        connection = DBConnectionFactory.getConnection();
        connection.setAutoCommit(false);
        String dbType = DBConnectionFactory.getDatabaseType(connection);
        String sql = getCreateTableScript(dbType, classDefinition);
        if (sql != null && sql.length() > 0) {
            statement = connection.createStatement();
            logger.info("create table " + classDefinition.getTableName() + ":\n" + sql);
            statement.execute(sql);
            JdbcUtils.close(statement);
            connection.commit();
            return sql;
        }
        return null;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(statement);
        JdbcUtils.close(connection);
    }
}

From source file:cz.vsb.gis.ruz76.gt.Examples.java

public String networking(String from, String to) {
    Connection conn;/*from   w w w  .  ja va  2  s. co m*/
    int nodefrom = 0;
    int nodeto = 0;
    long milis = System.currentTimeMillis();
    String name = "path" + String.valueOf(milis);
    try {
        Class.forName("org.postgresql.Driver");
        String url = "jdbc:postgresql://158.196.143.25:5432/test";
        conn = DriverManager.getConnection(url, "test", "test");

        Statement s = conn.createStatement();
        ResultSet r = s.executeQuery(
                "SELECT a.id municipalityid, b.id nodeid, ST_distance(a.geom,b.the_geom) AS distance FROM cr_wgs84.municipalities AS a, cr_wgs84.roads_vertices_pgr AS b WHERE ST_dwithin(a.geom,b.the_geom,2000) AND a.name = '"
                        + from + "' ORDER BY distance LIMIT 1");
        while (r.next()) {
            nodefrom = r.getInt(2);
        }
        r = s.executeQuery(
                "SELECT a.id municipalityid, b.id nodeid, ST_distance(a.geom,b.the_geom) AS distance FROM cr_wgs84.municipalities AS a, cr_wgs84.roads_vertices_pgr AS b WHERE ST_dwithin(a.geom,b.the_geom,2000) AND a.name = '"
                        + to + "' ORDER BY distance LIMIT 1");
        while (r.next()) {
            nodeto = r.getInt(2);
        }
        s.execute("DROP TABLE IF EXISTS " + name);

        s.execute("CREATE TABLE " + name
                + " AS SELECT seq, route.id1 AS node, route.id2 AS edge, route.cost, edges.geom FROM pgr_dijkstra('\n"
                + "   SELECT gid AS id,\n" + "         source::integer,\n" + "         target::integer,\n"
                + "         reverse_cost::double precision AS cost\n" + "   FROM cr_wgs84.roads',\n" + nodefrom
                + ", " + nodeto + ", false, false) \n" + "AS route, cr_wgs84.roads AS edges \n"
                + "WHERE route.id2 = edges.gid ORDER BY seq;");
        s.execute("SELECT UpdateGeometrySRID('" + name + "','geom',4326)");
        s.close();
        conn.close();
        publishPostGISTable(name);
    } catch (Exception e) {
        e.printStackTrace();
    }
    String ret = "Name from to:" + from + " " + to + "\n";
    ret += "Id from to:" + nodefrom + " " + nodeto + "\n";
    ret += "http://localhost:8080/geoserver/crwgs84/wms?service=WMS&version=1.1.&request=GetCapabilities"
            + "\n";
    ret += "Layer name:" + name + "\n";
    return ret;
}

From source file:com.glaf.core.util.DBUtils.java

public static String createTable(String systemName, TableDefinition classDefinition) {
    Connection connection = null;
    Statement statement = null;
    try {/*from   w  ww  . ja  va  2s  . co m*/
        connection = DBConnectionFactory.getConnection(systemName);
        connection.setAutoCommit(false);
        String dbType = DBConnectionFactory.getDatabaseType(connection);
        String sql = getCreateTableScript(dbType, classDefinition);
        if (sql != null && sql.length() > 0) {
            statement = connection.createStatement();
            logger.info("create table " + classDefinition.getTableName() + ":\n" + sql);
            statement.execute(sql);
            JdbcUtils.close(statement);
            connection.commit();
            return sql;
        }
        return null;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        JdbcUtils.close(statement);
        JdbcUtils.close(connection);
    }
}

From source file:com.photon.phresco.plugin.commons.PluginUtils.java

public void executeSql(SettingsInfo info, File basedir, String filePath, String fileName)
        throws PhrescoException {
    initDriverMap();//from w ww. j  av  a2  s  .c om
    String host = info.getPropertyInfo(Constants.DB_HOST).getValue();
    String port = info.getPropertyInfo(Constants.DB_PORT).getValue();
    String userName = info.getPropertyInfo(Constants.DB_USERNAME).getValue();
    String password = info.getPropertyInfo(Constants.DB_PASSWORD).getValue();
    String databaseName = info.getPropertyInfo(Constants.DB_NAME).getValue();
    String databaseType = info.getPropertyInfo(Constants.DB_TYPE).getValue();
    String version = info.getPropertyInfo(Constants.DB_VERSION).getValue();
    String connectionProtocol = findConnectionProtocol(databaseType, host, port, databaseName);
    Connection con = null;
    FileInputStream file = null;
    Statement st = null;
    try {
        Class.forName(getDbDriver(databaseType)).newInstance();
        file = new FileInputStream(basedir.getPath() + filePath + databaseType.toLowerCase() + File.separator
                + version + fileName);
        Scanner s = new Scanner(file);
        s.useDelimiter("(;(\r)?\n)|(--\n)");
        con = DriverManager.getConnection(connectionProtocol, userName, password);
        con.setAutoCommit(false);
        st = con.createStatement();
        while (s.hasNext()) {
            String line = s.next().trim();
            if (databaseType.equals("oracle")) {
                if (line.startsWith("--")) {
                    String comment = line.substring(line.indexOf("--"), line.lastIndexOf("--"));
                    line = line.replace(comment, "");
                    line = line.replace("--", "");
                }
                if (line.startsWith(Constants.REM_DELIMETER)) {
                    String comment = line.substring(0, line.lastIndexOf("\n"));
                    line = line.replace(comment, "");
                }
            }
            if (line.startsWith("/*!") && line.endsWith("*/")) {
                line = line.substring(line.indexOf("/*"), line.indexOf("*/") + 2);
            }
            if (line.trim().length() > 0) {
                st.execute(line);
            }
        }
    } catch (SQLException e) {
        throw new PhrescoException(e);
    } catch (FileNotFoundException e) {
        throw new PhrescoException(e);
    } catch (Exception e) {
        throw new PhrescoException(e);
    } finally {
        try {
            if (con != null) {
                con.commit();
                con.close();
            }
            if (file != null) {
                file.close();
            }
        } catch (Exception e) {
            throw new PhrescoException(e);
        }
    }
}