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:net.bull.javamelody.SpringTestFacadeImpl.java

/**
 * {@inheritDoc}/*from w  w  w  .j a  va 2 s  .  com*/
 */
@Override
public Date nowWithSql() throws SQLException {
    //      final javax.sql.DataSource dataSource = (javax.sql.DataSource) new javax.naming.InitialContext()
    //            .lookup("java:comp/env/jdbc/TestDB");
    final ApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] { "net/bull/javamelody/monitoring-spring.xml", "spring-context.xml", });
    final javax.sql.DataSource dataSource = (javax.sql.DataSource) context.getBean("dataSource");
    final java.sql.Connection connection = dataSource.getConnection();
    connection.setAutoCommit(false);
    try {
        // test pour explain plan en oracle
        //         final PreparedStatement statement = connection
        //               .prepareStatement("select * from v$session where user# = ?");
        final Statement statement = connection.createStatement();
        try {
            //            statement.setInt(1, 36);
            //            statement.executeQuery();

            statement.execute(
                    "DROP ALIAS if exists SLEEP; CREATE ALIAS SLEEP FOR \"java.lang.Thread.sleep(long)\"");
            statement.execute("call sleep(.01)");
            for (int i = 0; i < 5; i++) {
                statement.execute("call sleep(.02)");
            }
        } finally {
            statement.close();
        }
    } finally {
        connection.rollback();
        connection.close();
    }

    return new Date();
}

From source file:com.diversityarrays.dal.server.DalServer.java

static private void appendPossibleEntityTableDetails(SqlDalDatabase sqldb, String sql, StringBuilder sb)
        throws DalDbException {

    Connection conn = null;/*from  www . j  a va 2 s .c om*/
    Statement stmt = null;
    ResultSet rs = null;
    try {

        conn = sqldb.getConnection(false);

        stmt = conn.createStatement();

        // sb.append("<code>").append(DbUtil.htmlEscape(sql)).append("</code><hr/>");

        boolean hasResultSet = stmt.execute(sql);

        if (hasResultSet) {
            rs = stmt.getResultSet();
            DalServerUtil.appendResultSetRowsAsTable("No entity table", rs, sb);
        } else {
            int n = stmt.getUpdateCount();
            sb.append("Update count=").append(n);
        }
    } catch (SQLException e) {
        throw new DalDbException(e);
    } finally {
        SqlUtil.closeSandRS(stmt, rs);
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException ignore) {
            }
        }
    }

}

From source file:com.cloudera.sqoop.metastore.hsqldb.HsqldbMetaStore.java

/**
 * Connects to the server and instructs it to shutdown.
 *//*w w w .j a v  a2  s  . c o m*/
public void shutdown() {
    // Send the SHUTDOWN command to the server via SQL.
    SqoopOptions options = new SqoopOptions(conf);
    options.setConnectString("jdbc:hsqldb:hsql://localhost:" + port + "/sqoop");
    options.setUsername("SA");
    options.setPassword("");
    HsqldbManager manager = new HsqldbManager(options);
    Statement s = null;
    try {
        Connection c = manager.getConnection();
        s = c.createStatement();
        s.execute("SHUTDOWN");
    } catch (SQLException sqlE) {
        LOG.warn("Exception shutting down database: " + StringUtils.stringifyException(sqlE));
    } finally {
        if (null != s) {
            try {
                s.close();
            } catch (SQLException sqlE) {
                LOG.warn("Error closing statement: " + sqlE);
            }
        }

        try {
            manager.close();
        } catch (SQLException sqlE) {
            LOG.warn("Error closing manager: " + sqlE);
        }
    }
}

From source file:dk.teachus.backend.test.CreateMysqlTestDatabase.java

public void executeSql(Connection connection, CharSequence sql) throws SQLException {
    List<String> statements = parseSqlIntoSingleStatements(sql);

    for (String sqlStatement : statements) {
        Statement statement = null;

        try {/* w  ww . ja  va 2  s. com*/
            statement = connection.createStatement();
            statement.execute(sqlStatement);
        } catch (SQLSyntaxErrorException e) {
            System.err.println(sqlStatement);
            throw e;
        } finally {
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

From source file:de.klemp.middleware.controller.Controller.java

/**
 * With this method the devices can subscribe. Names as ID have to be
 * defined. The devices of the first component are saved in the table
 * "InputDevices". The devices of the second component are saved in the
 * table "OutputDevices"./* ww  w.j a  va2 s .  c  o m*/
 * 
 * @param component
 *            1 or 2
 * @param classes
 *            name of the class the device belong to
 * @param name
 *            name to be chosen
 */
@GET
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
@Path("/anmelden/{component}/{classes}/{name}")
public static synchronized String subscribe(@PathParam("component") int component,
        @PathParam("classes") String classes, @PathParam("name") String name) {
    String ok = "ok";
    createDBConnection();
    name.replaceAll("\"", "\\\"");
    try {
        if (component == 1) {
            PreparedStatement st = conn.prepareStatement("select class from \"Classes\" where class=?");
            st.setString(1, classes);
            ResultSet result = st.executeQuery();
            if (result.next()) {
                Statement statement = conn.createStatement();
                statement.execute("insert into \"" + classes + "\"(nameinput) values ('" + name + "');");
                st = conn.prepareStatement("insert into \"InputDevices\"(class,name) values (?,?);");
                st.setString(1, classes);
                st.setString(2, name);
                st.execute();

            } else {
                ok = "class not found";
            }

        }

        if (component == 2) {
            PreparedStatement st = conn.prepareStatement("select class from \"Classes\"where class=?");
            st.setString(1, classes);
            ResultSet result = st.executeQuery();
            if (result.next()) {
                deviceActive.put(classes + "," + name, true);
                createDBConnection();
                st = conn.prepareStatement(
                        "insert into \"OutputDevices\"(class,topic,enabled) values (?,?,'t');");
                st.setString(1, classes);
                st.setString(2, name);
                st.execute();

            } else {
                ok = "class not found";
            }
        }

    } catch (SQLException e) {

        String message = e.getMessage();
        if (!message.contains("doppelter Schlsselwert")) {
            logger.error("SQL Exception", e);
        }

    }
    closeDBConnection();
    return ok;
}

From source file:de.klemp.middleware.controller.Controller.java

/**
 * This method searches the methods from the classes of the first and the
 * second component. If a method of the second component needs a data, then
 * the String "Struktur fehlt" will be set in the column "data" of the table
 * "Classes". If a method does not need a data the column data is set="".
 */// ww  w.  j  a  v a2s .co m
public static synchronized void searchMethods() {
    createDBConnection();
    try {
        Statement statement = conn.createStatement();
        statement.execute("delete from \"Classes\";");
        statement.execute("delete from \"Data\";");
        structures.clear();
        PreparedStatement st = conn
                .prepareStatement("insert into \"Classes\" (component, class, method) values (?,?,?); ");

        ArrayList classes = getClasses(component1);
        Iterator iterator = classes.iterator();
        st.setInt(1, 1);
        while (iterator.hasNext()) {
            Object class1 = iterator.next();
            Method[] methods = class1.getClass().getDeclaredMethods();
            String name1 = class1.getClass().getName();
            String[] className = name1.split("\\.");
            st.setString(2, className[1]);
            for (int i = 0; i < methods.length; i++) {
                String name = methods[i].getName();
                st.setString(3, name);
                st.execute();
            }

        }
        classes = getClasses(component2);
        iterator = classes.iterator();
        st.setInt(1, 2);
        PreparedStatement st2 = conn
                .prepareStatement("insert into \"Data\" ( class, method,topic,data) values (?,?,?,?); ");
        while (iterator.hasNext()) {
            Object class2 = iterator.next();
            Method[] methods = class2.getClass().getDeclaredMethods();
            String name2 = class2.getClass().getName();
            String[] className = name2.split("\\.");
            st.setString(2, className[1]);
            st2.setString(1, className[1]);
            for (int i = 0; i < methods.length; i++) {
                String method = methods[i].getName();
                st2.setString(3, "");
                st.setString(3, method);
                st2.setString(2, method);
                Class<?>[] parameter = methods[i].getParameterTypes();
                for (int j = 0; j < parameter.length; j++) {
                    if (parameter[j].getName() == "Controller.Structure") {
                        st2.setString(4, "structure is missing");
                        st2.execute();
                        break;
                    }
                    if (parameter[j].getName() == "Controller.Sensor") {
                        st2.setString(4, "Sensor");
                        st2.execute();

                        break;
                    }

                }
                st.execute();
            }

        }
    } catch (SQLException e) {
        logger.error("SQL Exception", e);
    }
    closeDBConnection();
}

From source file:com.collective.celos.ci.testing.fixtures.deploy.hive.HiveTableDeployer.java

private void createMockedTable(Statement statement, String mockedDatabase, TestRun testRun) throws Exception {
    statement.execute(String.format(USE_DB_PATTERN, mockedDatabase));
    FixFile scriptFile = tableCreationScriptFile.create(testRun);
    String creationScript = IOUtils.toString(scriptFile.getContent());
    creationScript = creationScript.replace(SANDBOX_PARAM,
            testRun.getCiContext().getFileSystem().getUri() + testRun.getHdfsPrefix());
    statement.execute(creationScript);// www . j  av a 2  s . c  om
}

From source file:com.ianzepp.logging.jms.service.BasicDaoTest.java

/**
 * TODO Method description for <code>setUp()</code>
 * /*from   w ww  . j a va  2  s  .  c  om*/
 * @throws Exception
 */
@Before
public void setUp() throws Exception {
    // Create the tables
    Statement statement = getConnection().createStatement();
    statement.execute("DROP TABLE IF EXISTS \"EventException\"");
    statement.execute("DROP TABLE IF EXISTS \"EventLocation\"");
    statement.execute("DROP TABLE IF EXISTS \"EventUserRequest\"");
    statement.execute("DROP TABLE IF EXISTS \"Event\"");
    statement.execute(readFile("src/main/resources/com.ianzepp.logging.jms.service.CreateEventTable.sql"));
    statement.execute(
            readFile("src/main/resources/com.ianzepp.logging.jms.service.CreateEventExceptionTable.sql"));
    statement.execute(
            readFile("src/main/resources/com.ianzepp.logging.jms.service.CreateEventLocationTable.sql"));
    statement.execute(
            readFile("src/main/resources/com.ianzepp.logging.jms.service.CreateEventUserRequestTable.sql"));
}

From source file:fr.lip6.segmentations.ProcessHTML5.java

public void run() {
    //ArrayList<String> s1 = new ArrayList<String>();
    //ArrayList<String> s2= new ArrayList<String>();;
    String s1 = "";
    String s2 = "";
    try {//from  ww  w . j av  a2  s.  co m
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection(
                "jdbc:mysql://" + Config.mysqlHost + "/" + Config.mysqlDatabase + "", Config.mysqlUser,
                Config.mysqlPassword);
        Statement st2 = con.createStatement();
        ResultSet rs = st2.executeQuery("select * from html5repo where descriptorbom<>''");
        while (rs.next()) {
            s1 = "";
            s2 = "";
            String d1 = rs.getString("descriptor");
            String d2 = rs.getString("descriptorbom");
            int dsize = d1.split(",").length;
            int d2size = d2.split(",").length;
            for (String s : d1.split(",")) {
                String[] part = s.split("=");
                if (!part[0].equals("PAGE")) {
                    if (part[1].equals("SECTION"))
                        s1 += "S";
                    if (part[1].equals("ARTICLE"))
                        s1 += "A";
                    if (part[1].equals("ASIDE"))
                        s1 += "D";
                    if (part[1].equals("HEADER"))
                        s1 += "H";
                    if (part[1].equals("FOOTER"))
                        s1 += "F";
                    if (part[1].equals("NAV"))
                        s1 += "N";
                }
            }

            for (String s : d2.split(",")) {
                String[] part = s.split("=");
                if (!part[0].equals("PAGE")) {
                    if (part[1].equals("SECTION"))
                        s2 += "S";
                    if (part[1].equals("ARTICLE"))
                        s2 += "A";
                    if (part[1].equals("ASIDE"))
                        s2 += "D";
                    if (part[1].equals("HEADER"))
                        s2 += "H";
                    if (part[1].equals("FOOTER"))
                        s2 += "F";
                    if (part[1].equals("NAV"))
                        s2 += "N";
                }
            }
            int ed = StringUtils.getLevenshteinDistance(s1.toString(), s2.toString());
            int edtotal = Math.max(s1.length(), s2.length());
            HashSet<Character> h1 = new HashSet<Character>(), h2 = new HashSet<Character>();
            for (int i = 0; i < s1.length(); i++) {
                h1.add(s1.charAt(i));
            }
            for (int i = 0; i < s2.length(); i++) {
                h2.add(s2.charAt(i));
            }
            h1.retainAll(h2);
            int inter = h1.size();

            char[] code1 = s1.toCharArray();
            char[] code2 = s2.toCharArray();

            Set set1 = new HashSet();

            for (char c : code1) {
                set1.add(c);
            }

            Set set2 = new HashSet();

            for (char c : code2) {
                set2.add(c);
            }

            int total = set1.size();

            System.out.println(set1);
            System.out.println(set2);
            System.out.println(s1);
            System.out.println(s2);
            System.out.println(rs.getString("id") + ". " + rs.getString("datafolder") + "=" + ed + "/" + edtotal
                    + "=" + ((double) ed / edtotal) + "," + inter + " of " + total + " Prec:("
                    + ((double) inter / total) + ")");
            Statement st3 = con.createStatement();
            //base=distancemax
            st3.execute("update html5repo set distance='" + ed + "',base='" + edtotal + "',found='" + inter
                    + "', expected='" + total + "' where datafolder='" + rs.getString("datafolder") + "'");
            File f = new File("/home/sanojaa/Documents/00_Tesis/work/dataset/dataset/data/"
                    + rs.getString("datafolder") + "/" + rs.getString("datafolder") + ".5.html");
            if (!f.exists()) {
                f.createNewFile();
            }
            FileOutputStream fop = new FileOutputStream(f);
            fop.write(rs.getString("src").getBytes());
            fop.flush();
            fop.close();

        }
    } catch (SQLException ex) {
        Logger.getLogger(SeleniumWrapper.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(HTML5Bom.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(ProcessHTML5.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ProcessHTML5.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ccc.cli.Schema.java

private void execute(final Connection newConnection, final String statement) {
    try {//w  w  w  . ja va2  s. c om
        final Statement ps = newConnection.createStatement();

        try {
            ps.execute(statement.substring(0, statement.length() - 1));

        } finally {
            try {
                ps.close();
            } catch (final SQLException e) {
                swallow(e);
            }
        }
    } catch (final SQLException e) {
        LOG.warn("Failed to execute statement: " + statement + "\n > " + e.getMessage());
    }
}