Example usage for java.sql Statement executeQuery

List of usage examples for java.sql Statement executeQuery

Introduction

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

Prototype

ResultSet executeQuery(String sql) throws SQLException;

Source Link

Document

Executes the given SQL statement, which returns a single ResultSet object.

Usage

From source file:au.org.ala.layers.stats.ObjectsStatsGenerator.java

private static void updateArea(String fid) {

    try {/*  ww  w.  jav  a2  s  .  com*/
        Connection conn = getConnection();
        String sql = "SELECT pid from objects where area_km is null and st_geometrytype(the_geom) <> 'Point'";
        if (fid != null) {
            sql = sql + " and fid = '" + fid + "'";
        }

        sql = sql + " limit 200000;";

        System.out.println("loading area_km ...");
        Statement s1 = conn.createStatement();
        ResultSet rs1 = s1.executeQuery(sql);

        LinkedBlockingQueue<String> data = new LinkedBlockingQueue<String>();
        while (rs1.next()) {
            data.put(rs1.getString("pid"));
        }

        CountDownLatch cdl = new CountDownLatch(data.size());

        AreaThread[] threads = new AreaThread[CONCURRENT_THREADS];
        for (int j = 0; j < CONCURRENT_THREADS; j++) {
            threads[j] = new AreaThread(data, cdl, getConnection().createStatement());
            threads[j].start();
        }

        cdl.await();

        for (int j = 0; j < CONCURRENT_THREADS; j++) {
            threads[j].s.close();
            threads[j].interrupt();
        }
        rs1.close();
        s1.close();
        conn.close();
        return;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return;
}

From source file:application.bbdd.pool.java

public static void realizaConsulta2() {
    Connection conexion = null;/*from   w w w.  j a v a2  s  .  c om*/
    Statement sentencia = null;
    ResultSet rs = null;

    try {
        conexion = getConexion();
        sentencia = conexion.createStatement();
        rs = sentencia.executeQuery("select count(*) from db");
        rs.next();
        JOptionPane.showMessageDialog(null, "El numero de bd es: " + rs.getInt(1));
        logStatistics();

    } catch (SQLException e) {
        JOptionPane.showMessageDialog(null, e.toString());
    } finally {
        try {
            rs.close();
            sentencia.close();
            liberaConexion(conexion);
        } catch (Exception fe) {
            JOptionPane.showMessageDialog(null, fe.toString());
        }
    }
}

From source file:bizlogic.Sensors.java

public static void list(Connection DBcon) throws IOException, ParseException, SQLException {

    Statement st = null;
    ResultSet rs = null;/*from w  w w .  j  a v  a2 s. com*/

    try {
        st = DBcon.createStatement();
        rs = st.executeQuery("SELECT * FROM USERCONF.SENSORLIST");

    } catch (SQLException ex) {
        Logger lgr = Logger.getLogger(Sensors.class.getName());
        lgr.log(Level.SEVERE, ex.getMessage(), ex);
    }
    try {
        FileWriter sensorsFile = new FileWriter("/var/lib/tomcat8/webapps/ROOT/Records/sensors.json");
        sensorsFile.write("");
        sensorsFile.flush();

        JSONParser parser = new JSONParser();

        JSONObject Records = new JSONObject();

        JSONObject operation_Obj = new JSONObject();
        JSONObject operand_Obj = new JSONObject();
        JSONObject unit_Obj = new JSONObject();
        JSONObject name_Obj = new JSONObject();
        JSONObject ip_Obj = new JSONObject();
        JSONObject port_Obj = new JSONObject();

        int _total = 0;

        JSONArray sensorList = new JSONArray();

        while (rs.next()) {

            JSONObject sensor_Obj = new JSONObject();
            int id = rs.getInt("sensor_id");
            String operation = rs.getString("operation");
            int operand = rs.getInt("operand");
            String unit = rs.getString("unit");
            String name = rs.getString("name");
            String ip = rs.getString("IP");
            int port = rs.getInt("port");

            sensor_Obj.put("recid", id);
            sensor_Obj.put("operation", operation);
            sensor_Obj.put("operand", operand);
            sensor_Obj.put("unit", unit);
            sensor_Obj.put("name", name);
            sensor_Obj.put("IP", ip);
            sensor_Obj.put("port", port);

            sensorList.add(sensor_Obj);
            _total++;

        }
        rs.close();

        Records.put("total", _total);
        Records.put("records", sensorList);

        sensorsFile.write(Records.toJSONString());
        sensorsFile.flush();
        sensorsFile.close();
    }

    catch (IOException ex) {
        Logger.getLogger(Sensors.class.getName()).log(Level.WARNING, null, ex);
    }
}

From source file:com.oracle.tutorial.jdbc.DatalinkSample.java

public static void viewTable(Connection con, Proxy proxy) throws SQLException, IOException {
    Statement stmt = null;
    String query = "SELECT document_name, url FROM data_repository";

    try {//from ww  w . ja v a2 s.co m
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(query);

        if (rs.next()) {
            String documentName = null;
            java.net.URL url = null;

            documentName = rs.getString(1);

            // Retrieve the value as a URL object.
            url = rs.getURL(2);

            if (url != null) {

                // Retrieve the contents from the URL.
                URLConnection myURLConnection = url.openConnection(proxy);
                BufferedReader bReader = new BufferedReader(
                        new InputStreamReader(myURLConnection.getInputStream()));

                System.out.println("Document name: " + documentName);

                String pageContent = null;

                while ((pageContent = bReader.readLine()) != null) {
                    // Print the URL contents
                    System.out.println(pageContent);
                }
            } else {
                System.out.println("URL is null");
            }
        }
    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    } catch (IOException ioEx) {
        System.out.println("IOException caught: " + ioEx.toString());
    } catch (Exception ex) {
        System.out.println("Unexpected exception");
        ex.printStackTrace();
    } finally {
        if (stmt != null) {
            stmt.close();
        }
    }
}

From source file:io.cloudslang.content.database.services.SQLQueryService.java

public static void executeSqlQuery(@NotNull final SQLInputs sqlInputs) throws Exception {
    if (StringUtils.isEmpty(sqlInputs.getSqlCommand())) {
        throw new Exception("command input is empty.");
    }/*from w w w  . j a  v a 2s .c  om*/
    ConnectionService connectionService = new ConnectionService();
    try (final Connection connection = connectionService.setUpConnection(sqlInputs)) {

        connection.setReadOnly(true);
        Statement statement = connection.createStatement(sqlInputs.getResultSetType(),
                sqlInputs.getResultSetConcurrency());
        statement.setQueryTimeout(sqlInputs.getTimeout());
        final ResultSet results = statement.executeQuery(sqlInputs.getSqlCommand());

        final ResultSetMetaData mtd = results.getMetaData();

        int iNumCols = mtd.getColumnCount();

        final StringBuilder strColumns = new StringBuilder(sqlInputs.getStrColumns());

        for (int i = 1; i <= iNumCols; i++) {
            if (i > 1) {
                strColumns.append(sqlInputs.getStrDelim());
            }
            strColumns.append(mtd.getColumnLabel(i));
        }
        sqlInputs.setStrColumns(strColumns.toString());

        while (results.next()) {
            final StringBuilder strRowHolder = new StringBuilder();
            for (int i = 1; i <= iNumCols; i++) {
                if (i > 1)
                    strRowHolder.append(sqlInputs.getStrDelim());
                if (results.getString(i) != null) {
                    String value = results.getString(i).trim();
                    if (sqlInputs.isNetcool())
                        value = SQLUtils.processNullTerminatedString(value);

                    strRowHolder.append(value);
                }
            }
            sqlInputs.getLRows().add(strRowHolder.toString());
        }
    }
}

From source file:org.mitre.jdbc.datasource.H2DataSourceFactory.java

protected static ResultSet executeQuery(Connection conn, String executeScriptQuery) throws SQLException {
    Statement statement = conn.createStatement();
    return statement.executeQuery(executeScriptQuery);

}

From source file:bullioneconomy.bullionchart.java

/**
 * Creates a dataset, consisting of two series of monthly data.
 *
 * @return The dataset./*from ww  w  . j  a v a  2s . c om*/
 */
private static XYDataset createDataset() throws ClassNotFoundException, SQLException, ParseException {

    TimeSeries s1 = new TimeSeries("Actual", Day.class);
    TimeSeries s2 = new TimeSeries("Forecasted", Day.class);
    Class.forName("com.mysql.jdbc.Driver");
    try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/BULLION", "yajnab",
            "petrol123")) {
        Statement stmt = con.createStatement();
        ResultSet result = stmt.executeQuery("SELECT * FROM gold");
        ArrayList<Double> arm = new ArrayList<>();
        predictor pcd = new predictor();
        arm = pcd.ARIMApredict();
        int i = 0;
        while (result.next()) {

            String datefeed = result.getString(1);
            Double value = result.getDouble(2);
            int[] m = new int[3];
            //bullionchart bcc = new bullionchart();
            //m = bcc.dateget(datefeed);
            m = dateget(datefeed);
            s1.add(new Day(m[0], m[1], m[2]), value);
            s2.add(new Day(m[0], m[1], m[2]), arm.get(i));
            i++;
        }
        result.close();
        /*s1.add(new Month(2, 2001), 181.8);
        s1.add(new Month(3, 2001), 167.3);
        s1.add(new Month(4, 2001), 153.8);
        s1.add(new Month(5, 2001), 167.6);
        s1.add(new Month(6, 2001), 158.8);
        s1.add(new Month(7, 2001), 148.3);
        s1.add(new Month(8, 2001), 153.9);
        s1.add(new Month(9, 2001), 142.7);
        s1.add(new Month(10, 2001), 123.2);
        s1.add(new Month(11, 2001), 131.8);
        s1.add(new Month(12, 2001), 139.6);
        s1.add(new Month(1, 2002), 142.9);
        s1.add(new Month(2, 2002), 138.7);
        s1.add(new Month(3, 2002), 137.3);
        s1.add(new Month(4, 2002), 143.9);
        s1.add(new Month(5, 2002), 139.8);
        s1.add(new Month(6, 2002), 137.0);
        s1.add(new Month(7, 2002), 132.8);*/
    }

    /*TimeSeries s2 = new TimeSeries("Forecasted", Month.class);
    s2.add(new Month(2, 2001), 129.6);
    s2.add(new Month(3, 2001), 123.2);
    s2.add(new Month(4, 2001), 117.2);
    s2.add(new Month(5, 2001), 124.1);
    s2.add(new Month(6, 2001), 122.6);
    s2.add(new Month(7, 2001), 119.2);
    s2.add(new Month(8, 2001), 116.5);
    s2.add(new Month(9, 2001), 112.7);
    s2.add(new Month(10, 2001), 101.5);
    s2.add(new Month(11, 2001), 106.1);
    s2.add(new Month(12, 2001), 110.3);
    s2.add(new Month(1, 2002), 111.7);
    s2.add(new Month(2, 2002), 111.0);
    s2.add(new Month(3, 2002), 109.6);
    s2.add(new Month(4, 2002), 113.2);
    s2.add(new Month(5, 2002), 111.6);
    s2.add(new Month(6, 2002), 108.8);
    s2.add(new Month(7, 2002), 101.6);*/

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(s1);
    dataset.addSeries(s2);

    dataset.setDomainIsPointsInTime(true);

    return dataset;

}

From source file:com.oracle.tutorial.jdbc.SuppliersTable.java

public static void viewTable(Connection con) throws SQLException {
    Statement stmt = null;
    String query = "select SUP_ID, SUP_NAME, STREET, CITY, STATE, ZIP from SUPPLIERS";
    try {/*from  www . ja  v a2 s .  co  m*/
        stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        while (rs.next()) {
            int supplierID = rs.getInt("SUP_ID");
            String supplierName = rs.getString("SUP_NAME");
            String street = rs.getString("STREET");
            String city = rs.getString("CITY");
            String state = rs.getString("STATE");
            String zip = rs.getString("ZIP");
            System.out.println(
                    supplierName + "(" + supplierID + "): " + street + ", " + city + ", " + state + ", " + zip);
        }
    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    } finally {
        if (stmt != null) {
            stmt.close();
        }
    }
}

From source file:org.usip.osp.graphs.GraphServer.java

public static Chart getChartByNameAndRound(String chart_id, String game_round, String sim_id,
        String values_table) {/*from   ww  w . j  a va  2 s  . c  o m*/

    Chart cci = new Chart();

    String selectChartInfo = "SELECT * FROM `charts` where sf_id = '" //$NON-NLS-1$
            + chart_id + "'"; //$NON-NLS-1$

    try {
        Connection connection = MultiSchemaHibernateUtil.getConnection();
        Statement stmt = connection.createStatement();
        ResultSet rst = stmt.executeQuery(selectChartInfo);

        if (rst.next()) {
            String chart_type = rst.getString("type"); //$NON-NLS-1$
            String chart_title = rst.getString("title"); //$NON-NLS-1$
            String x_axis_title = rst.getString("x_axis_title"); //$NON-NLS-1$
            String y_axis_title = rst.getString("y_axis_title"); //$NON-NLS-1$

            //cci.height = rst.getInt("height");
            //cci.width = rst.getInt("width");

            String howToGetData = rst.getString("first_data_source"); //$NON-NLS-1$

            howToGetData = howToGetData.replace("[simulation_id]", sim_id); //$NON-NLS-1$
            howToGetData = howToGetData.replace("[sim_value_table_name]", values_table); //$NON-NLS-1$

            Statement stmt2 = connection.createStatement();
            ResultSet rst2 = stmt.executeQuery(howToGetData);

            JFreeChart chart = null;

            if (chart_type.equalsIgnoreCase("LineChart")) { //$NON-NLS-1$

                DefaultCategoryDataset cd = DataGatherer.getChartData(chart_type, game_round, howToGetData);

                chart = ChartFactory.createLineChart(chart_title, // chart
                        // title
                        x_axis_title, // domain axis label
                        y_axis_title, // range axis label
                        cd, // data
                        PlotOrientation.VERTICAL, // orientation
                        false, // include legend
                        true, // tooltips
                        false // urls
                );

            } else if (chart_type.equalsIgnoreCase("BarChart")) { //$NON-NLS-1$

                DefaultPieDataset dataset = DataGatherer.getPieData(chart_id, game_round, howToGetData);

                chart = ChartFactory.createPieChart(chart_title, dataset, true, // legend?
                        true, // tooltips?
                        false // URLs?
                );
            }

            cci.setThis_chart(chart);

        } // End of loop if found chart info

        connection.close();

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

    return cci;
}

From source file:Student.java

  public static void checkData() throws Exception {
  Class.forName("org.hsqldb.jdbcDriver");
  Connection conn = DriverManager.getConnection("jdbc:hsqldb:data/tutorial", "sa", "");
  Statement st = conn.createStatement();

  ResultSet mrs = conn.getMetaData().getTables(null, null, null, new String[] { "TABLE" });
  while (mrs.next()) {
    String tableName = mrs.getString(3);
    System.out.println("\n\n\n\nTable Name: "+ tableName);

    ResultSet rs = st.executeQuery("select * from " + tableName);
    ResultSetMetaData metadata = rs.getMetaData();
    while (rs.next()) {
      System.out.println(" Row:");
      for (int i = 0; i < metadata.getColumnCount(); i++) {
        System.out.println("    Column Name: "+ metadata.getColumnLabel(i + 1)+ ",  ");
        System.out.println("    Column Type: "+ metadata.getColumnTypeName(i + 1)+ ":  ");
        Object value = rs.getObject(i + 1);
        System.out.println("    Column Value: "+value+"\n");
      }//w w w. ja  va 2s  .c  om
    }
  }
}