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:helma.objectmodel.db.Transactor.java

/**
 * Get a db connection that was previously registered with this transactor thread.
 * @param src the db source//from   w  w w  .ja  va2 s .c o  m
 * @return the connection
 */
public Connection getConnection(DbSource src) {
    Connection con = (Connection) sqlConnections.get(src);
    Long tested = (Long) testedConnections.get(src);
    long now = System.currentTimeMillis();
    if (con != null && (tested == null || now - tested.longValue() > 60000)) {
        // Check if the connection is still alive by executing a simple statement.
        try {
            Statement stmt = con.createStatement();
            stmt.execute("SELECT 1");
            stmt.close();
            testedConnections.put(src, new Long(now));
        } catch (SQLException sx) {
            try {
                con.close();
            } catch (SQLException ignore) {
                /* nothing to do */}
            return null;
        }
    }
    return con;
}

From source file:com.facebook.presto.accumulo.tools.PaginationTask.java

public int runQuery() throws SQLException {
    int numErrors = 0;
    numErrors += checkParam(config, "config");
    numErrors += checkParam(host, "host");
    numErrors += checkParam(port, "port");
    numErrors += checkParam(query, "query");
    numErrors += checkParam(columns, "columns");

    if (numErrors > 0) {
        return 1;
    }/* w  ww.  j av a2 s. c om*/

    // Clean up any previously run queries in the event the user did not call it explicitly
    cleanup();

    // Open JDBC connection
    String dbUrl = String.format("%s%s:%d/%s", SCHEME, host, port, CATALOG);
    Properties jdbcProps = new Properties();
    jdbcProps.setProperty("user", "root");
    conn = (PrestoConnection) DriverManager.getConnection(dbUrl, jdbcProps);
    conn.setCatalog(CATALOG);
    setSessionProperties(conn);

    // Randomly generate a table name as a local variable
    String tmpTable = "accumulo.pagination.tmp_" + UUID.randomUUID().toString().replaceAll("\\W", "");

    // Build the column mapping based on
    StringBuilder columnMapping = new StringBuilder();
    for (String col : columns) {
        columnMapping.append(col).append(":f:").append(UUID.randomUUID().toString().substring(0, 8))
                .append(',');
    }
    columnMapping.deleteCharAt(columnMapping.length() - 1);

    StringBuilder queryWithGroupBy = new StringBuilder("SELECT 0 AS groupby, ");
    queryWithGroupBy.append(query.substring(query.indexOf("SELECT ") + 7));

    // Substitute the parameters to generate the create table query
    Map<String, String> queryProps = new HashMap<>();
    queryProps.put(TMP_TABLE, tmpTable);
    queryProps.put(TMP_COLUMN_MAPPING, columnMapping.toString());
    queryProps.put(SUBQUERY_COLUMNS, StringUtils.join(columns, ','));
    queryProps.put(USER_QUERY, queryWithGroupBy.toString());

    // Execute the create table query
    StrSubstitutor sub = new StrSubstitutor(queryProps);
    String createTableQuery = sub.replace(createTableTemplate);
    LOG.info(format("Executing query to create temporary table:\n%s", createTableQuery));
    Statement stmt = conn.createStatement();
    stmt.execute(createTableQuery);

    // Execute the query to get the max offset i.e. number of rows from the user query
    stmt = conn.createStatement();
    ResultSet results = stmt.executeQuery("SELECT MAX(offset) FROM " + tmpTable);
    results.next();
    maxOffset = results.getLong(1);
    LOG.info(format("Query has %d results", maxOffset));

    // Set the temp table name now that we have made it through the gauntlet
    this.tmpTableName = tmpTable;
    return 0;
}

From source file:com.hangum.tadpole.rdb.core.editors.main.execute.sub.ExecuteOtherSQL.java

/**
 * select ??  //w  w  w.ja  v  a 2s.  c om
 * 
 * @param reqQuery
 * @exception
 */
public static void runSQLOther(final RequestQuery reqQuery, final UserDBDAO userDB, final String userType,
        final String userEmail) throws SQLException, Exception {

    // is tajo
    if (DBDefine.TAJO_DEFAULT == userDB.getDBDefine()) {
        new TajoConnectionManager().executeUpdate(userDB, reqQuery.getSql());
    } else {

        // commit rollback ?   .
        if (TransactionManger.calledCommitOrRollback(reqQuery.getSql(), userEmail, userDB))
            return;

        java.sql.Connection javaConn = null;
        Statement statement = null;
        try {
            if (reqQuery.isAutoCommit()) {
                SqlMapClient client = TadpoleSQLManager.getInstance(userDB);
                javaConn = client.getDataSource().getConnection();
            } else {
                javaConn = TadpoleSQLTransactionManager.getInstance(userEmail, userDB);
            }
            statement = javaConn.createStatement();

            // TODO mysql?  https://github.com/hangum/TadpoleForDBTools/issues/3  ?   create table ? ?? '(' ?? ? ?? .
            if (userDB.getDBDefine() == DBDefine.MYSQL_DEFAULT
                    || userDB.getDBDefine() == DBDefine.MARIADB_DEFAULT) {
                final String checkSQL = reqQuery.getSql().trim().toUpperCase();
                if (StringUtils.startsWithIgnoreCase(checkSQL, "CREATE TABLE")) { //$NON-NLS-1$
                    reqQuery.setSql(StringUtils.replaceOnce(reqQuery.getSql(), "(", " (")); //$NON-NLS-1$ //$NON-NLS-2$
                }
            }

            // hive executeUpdate() ? . 13.08.19-hangum
            if (userDB.getDBDefine() == DBDefine.HIVE_DEFAULT || userDB.getDBDefine() == DBDefine.HIVE2_DEFAULT
                    || userDB.getDBDefine() == DBDefine.SQLite_DEFAULT) {

                statement.execute(reqQuery.getSql());

            } else {
                statement.executeUpdate(reqQuery.getSql());
            }

        } finally {
            try {
                statement.close();
            } catch (Exception e) {
            }

            if (reqQuery.isAutoCommit()) {
                try {
                    javaConn.close();
                } catch (Exception e) {
                }
            }
        }
    } // end which db
}

From source file:com.splicemachine.derby.test.framework.SpliceFunctionWatcher.java

@Override
protected void starting(Description description) {
    LOG.trace("Starting");
    Connection connection = null;
    Statement statement = null;
    ResultSet rs = null;//ww w .ja va2 s .  c  o m
    try {
        connection = (userName == null) ? SpliceNetConnection.getConnection()
                : SpliceNetConnection.getConnectionAs(userName, password);
        rs = connection.getMetaData().getTables(null, schemaName, functionName, null);
        if (rs.next()) {
            executeDrop(schemaName, functionName);
        }
        connection.commit();
        statement = connection.createStatement();
        statement.execute(CREATE_FUNCTION + schemaName + "." + functionName + " " + createString);
        connection.commit();
    } catch (Exception e) {
        LOG.error("Create function statement is invalid ");
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(statement);
        DbUtils.commitAndCloseQuietly(connection);
    }
    super.starting(description);
}

From source file:com.iver.utiles.connections.ConnectionDB.java

/**
 * Executes a query/* w ww .  j  a  va 2s .  c  om*/
 * 
 * @param SQL
 *            query
 * @param name
 *            Drivers name
 * 
 * @throws ConnectionException
 */
public void ejecutaSQLnors(String SQL, String name) throws ConnectionException {
    Connection conn = null;
    Statement s = null;

    try {
        try {
            conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:" + name);

            s = conn.createStatement();
            s.execute(SQL);
        } catch (SQLException e) {
            throw new ConnectionException(JDBCManager.getTranslation("fallo_realizar_consulta"), e);
        }
    } finally {
        try {
            s.close();
        } catch (Exception e) {
        }

        try {
            conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:jp.co.tis.gsp.tools.dba.dialect.PostgresqlDialect.java

@Override
public void createUser(String user, String password, String adminUser, String adminPassword)
        throws MojoExecutionException {
    Connection conn = null;// w  ww.jav  a 2s .c  om
    Statement stmt = null;
    String database = getDatabase();
    String role = StringUtils.lowerCase(user);
    try {
        conn = DriverManager.getConnection(url, adminUser, adminPassword);
        stmt = conn.createStatement();
        if (existsUser(conn, role)) {
            return;
        }

        stmt.execute("CREATE ROLE " + role + " LOGIN PASSWORD \'" + password + "\'");
        stmt.execute("GRANT CREATE, CONNECT ON DATABASE " + database + " TO " + role);
    } catch (SQLException e) {
        throw new MojoExecutionException("CREATE USER?", e);
    } finally {
        StatementUtil.close(stmt);
        ConnectionUtil.close(conn);
    }
}

From source file:com.splicemachine.derby.test.framework.SpliceViewWatcher.java

@Override
public void starting(Description description) {
    LOG.trace("Starting");
    Connection connection = null;
    Statement statement = null;
    ResultSet rs = null;/*from w  ww .j  a v  a  2  s .c om*/
    try {
        connection = userName == null ? SpliceNetConnection.getConnection()
                : SpliceNetConnection.getConnectionAs(userName, password);
        rs = connection.getMetaData().getTables(null, schemaName, viewName, null);
        if (rs.next()) {
            executeDrop(schemaName, viewName);
        }
        connection.commit();
        statement = connection.createStatement();
        statement.execute(CREATE_VIEW + schemaName + "." + viewName + " " + createString);
        connection.commit();
    } catch (Exception e) {
        LOG.error("Create view statement is invalid ");
        e.printStackTrace(System.err);
        throw new RuntimeException(e);
    } finally {
        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(statement);
        DbUtils.commitAndCloseQuietly(connection);
    }
    super.starting(description);
}

From source file:com.haulmont.cuba.core.sys.dbupdate.DbUpdaterEngine.java

protected void executeSql(String sql) throws SQLException {
    Connection connection = null;
    Statement statement = null;
    try {//ww  w  .  j av a 2s.  c om
        connection = getDataSource().getConnection();
        statement = connection.createStatement();
        statement.execute(sql);
    } finally {
        DbUtils.closeQuietly(statement);
        DbUtils.closeQuietly(connection);
    }
}

From source file:eu.optimis_project.monitoring.storage.MySQLStorageManager.java

public void dropTable() throws SQLException {
    final String createTable = "DROP TABLE IF EXISTS " + tableName + ";";

    Statement statement = null;
    try {/*from  w w  w .  ja v  a 2s . co  m*/
        log.debug("Executing query: " + createTable);
        statement = getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_UPDATABLE);
        statement.execute(createTable);
    } catch (SQLException e) {
        throw e;
    } finally {
        try {
            if (statement != null) {
                statement.close();
            }
        } catch (SQLException e) {
            log.debug("Failed to close statement.", e);
        }
    }
}

From source file:jp.co.tis.gsp.tools.dba.dialect.SqlserverDialect.java

@Override
public void dropAll(String user, String password, String adminUser, String adminPassword, String schema)
        throws MojoExecutionException {
    Connection conn = null;//from  w w  w . j  a  v  a  2  s .co  m
    Statement stmt = null;
    PreparedStatement dropStmt;
    try {
        conn = DriverManager.getConnection(url, adminUser, adminPassword);
        stmt = conn.createStatement();

        // ???????
        if (!existsSchema(conn, schema)) {
            stmt.execute("CREATE SCHEMA " + schema);
            conn.createStatement().execute("ALTER USER " + user + " WITH DEFAULT_SCHEMA = " + schema);

            if (!StringUtils.equalsIgnoreCase(schema, "dbo") && !StringUtils.equalsIgnoreCase(schema, "sys")
                    && !StringUtils.equalsIgnoreCase(schema, "INFORMATION_SCHEMA")) {
                stmt.execute("ALTER AUTHORIZATION ON SCHEMA::" + schema + " TO " + user);
            }

            return;
        } else {
            conn.createStatement().execute("ALTER USER " + user + " WITH DEFAULT_SCHEMA = " + schema);

            if (!StringUtils.equalsIgnoreCase(schema, "dbo") && !StringUtils.equalsIgnoreCase(schema, "sys")
                    && !StringUtils.equalsIgnoreCase(schema, "INFORMATION_SCHEMA")) {
                stmt.execute("ALTER AUTHORIZATION ON SCHEMA::" + schema + " TO " + user);
            }
        }

        // ????
        EntityDependencyParser parser = new EntityDependencyParser();
        parser.parse(conn, url, schema);
        final List<String> tableList = parser.getTableList();
        Collections.reverse(tableList);
        for (String table : tableList) {
            dropObject(conn, schema, "TABLE", table);
        }

        // ??
        dropStmt = conn.prepareStatement("SELECT name, type_desc FROM sys.objects WHERE schema_id = SCHEMA_ID('"
                + schema + "') AND type IN ('U','V')");
        ResultSet rs = dropStmt.executeQuery();
        while (rs.next()) {
            if (!tableList.contains(rs.getString("name"))) {
                String objectType = getObjectType(rs.getString("type_desc"));
                if (objectType != null) {
                    dropObject(conn, schema, objectType, rs.getString("name"));
                }
            }
        }
    } catch (SQLException e) {
        throw new MojoExecutionException("?", e);
    } finally {
        StatementUtil.close(stmt);
        ConnectionUtil.close(conn);
    }
}