Example usage for java.sql PreparedStatement executeQuery

List of usage examples for java.sql PreparedStatement executeQuery

Introduction

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

Prototype

ResultSet executeQuery() throws SQLException;

Source Link

Document

Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Connection dbConnection = null;
    PreparedStatement preparedStatement = null;
    Class.forName(DB_DRIVER);/*from   w  w  w .ja  v  a  2 s.c o  m*/
    dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);

    String selectSQL = "SELECT USER_ID, USERNAME FROM Person WHERE USER_ID = ?";
    preparedStatement = dbConnection.prepareStatement(selectSQL);
    preparedStatement.setInt(1, 1001);

    ResultSet rs = preparedStatement.executeQuery();

    while (rs.next()) {

        String userid = rs.getString("USER_ID");
        String username = rs.getString("USERNAME");

        System.out.println("userid : " + userid);
        System.out.println("username : " + username);

    }

    preparedStatement.close();
    dbConnection.close();

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getHSQLConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("create table survey (id int,name varchar);");
    st.executeUpdate("create view surveyView as (select * from survey);");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");
    st.executeUpdate("insert into survey (id,name ) values (2,'anotherValue')");

    ResultSet rs = null;/* w  w w. j a  v a2  s. c o  m*/
    PreparedStatement ps = null;

    String query = "select id, name from survey where id = ?";

    ps = conn.prepareStatement(query);
    // specify values for all input parameters
    ps.setInt(1, 001); // set the first parameter: id

    // now, PreparedStatement object is ready to be executed.
    rs = ps.executeQuery();
    // iterate the result set object
    while (rs.next()) {
        int id = rs.getInt(1);
        String name = rs.getString(2);
        System.out.println("[id=" + id + "][name=" + name + "]");
    }

    // NOTE: you may use PreparedStatement as many times as you want
    // here we use it for another set of parameters:
    ps.setInt(1, 002); // set the first parameter: id

    // now, PreparedStatement object is ready to be executed.
    rs = ps.executeQuery();
    // iterate the result set object
    while (rs.next()) {
        int id = rs.getInt(1);
        String name = rs.getString(2);
        System.out.println("[id=" + id + "][name=" + name + "]");
    }
    rs.close();
    ps.close();
    conn.close();

}

From source file:DeliverWork.java

public static void main(String[] args) throws UnsupportedEncodingException, MessagingException {
    JdbcFactory jdbcFactoryChanye = new JdbcFactory(
            "jdbc:mysql://127.0.0.1:3306/fp_guimin?useUnicode=true&characterEncoding=UTF-8", "guimin_db",
            "guimin@98fhi3p2hUFHfdfoi", "com.mysql.jdbc.Driver");
    connection = jdbcFactoryChanye.getConnection();
    Map<String, String> map = new HashMap();

    try {//from  w  w  w.  j a v  a 2s.  c o  m
        PreparedStatement ps = connection.prepareStatement(selectAccount);
        ResultSet resultSet = ps.executeQuery();
        while (resultSet.next()) {
            map.put(resultSet.getString(1), resultSet.getString(2));
        }
        ps.close();
        map.forEach((k, v) -> {
            syncTheFile(k, v);
        });
        connection.close();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String deptName = "oldName";
    String newDeptName = "newName";

    ResultSet rs = null;//  w ww.  j  av  a 2s . c om
    Connection conn = null;
    PreparedStatement pstmt = null;
    PreparedStatement pstmt2 = null;
    try {
        conn = getConnection();
        // prepare query for getting a REF object and PrepareStatement object
        String refQuery = "select manager from dept_table where dept_name=?";
        pstmt = conn.prepareStatement(refQuery);
        pstmt.setString(1, deptName);
        rs = pstmt.executeQuery();
        java.sql.Ref ref = null;
        if (rs.next()) {
            ref = rs.getRef(1);
        }
        if (ref == null) {
            System.out.println("error: could not get a reference for manager.");
            System.exit(1);
        }
        String query = "INSERT INTO dept_table(dept_name, manager)values(?, ?)";
        pstmt2 = conn.prepareStatement(query);
        pstmt2.setString(1, newDeptName);
        pstmt2.setRef(2, ref);
        // execute query, and return number of rows created
        int rowCount = pstmt2.executeUpdate();
        System.out.println("rowCount=" + rowCount);
    } finally {
        pstmt.close();
        pstmt2.close();
        conn.close();
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String deptName = "oldName";
    String newDeptName = "newName";

    ResultSet rs = null;/*  w w w .  j  a v a2  s.  c o m*/
    Connection conn = null;
    PreparedStatement pstmt = null;
    PreparedStatement pstmt2 = null;
    try {
        conn = getConnection();
        // prepare query for getting a REF object and PrepareStatement object
        String refQuery = "select manager from dept_table where dept_name=?";
        pstmt = conn.prepareStatement(refQuery);
        pstmt.setString(1, deptName);
        rs = pstmt.executeQuery();
        java.sql.Ref ref = null;
        if (rs.next()) {
            ref = rs.getRef("manager");
        }
        if (ref == null) {
            System.out.println("error: could not get a reference for manager.");
            System.exit(1);
        }
        String query = "INSERT INTO dept_table(dept_name, manager)values(?, ?)";
        pstmt2 = conn.prepareStatement(query);
        pstmt2.setString(1, newDeptName);
        pstmt2.setRef(2, ref);
        // execute query, and return number of rows created
        int rowCount = pstmt2.executeUpdate();
        System.out.println("rowCount=" + rowCount);
    } finally {
        pstmt.close();
        pstmt2.close();
        conn.close();
    }
}

From source file:Blobs.java

public static void main(String args[]) {
    if (args.length != 1) {
        System.err.println("Syntax: <java Blobs [driver] [url] " + "[uid] [pass] [file]");
        return;// w  w w  .  j av a 2s .c o  m
    }
    try {
        Class.forName(args[0]).newInstance();
        Connection con = DriverManager.getConnection(args[1], args[2], args[3]);
        File f = new File(args[4]);
        PreparedStatement stmt;

        if (!f.exists()) {
            // if the file does not exist
            // retrieve it from the database and write it to the named file
            ResultSet rs;

            stmt = con.prepareStatement("SELECT blobData " + "FROM BlobTest " + "WHERE fileName = ?");

            stmt.setString(1, args[0]);
            rs = stmt.executeQuery();
            if (!rs.next()) {
                System.out.println("No such file stored.");
            } else {
                Blob b = rs.getBlob(1);
                BufferedOutputStream os;

                os = new BufferedOutputStream(new FileOutputStream(f));
                os.write(b.getBytes(0, (int) b.length()), 0, (int) b.length());
                os.flush();
                os.close();
            }
        } else {
            // otherwise read it and save it to the database
            FileInputStream fis = new FileInputStream(f);
            byte[] tmp = new byte[1024];
            byte[] data = null;
            int sz, len = 0;

            while ((sz = fis.read(tmp)) != -1) {
                if (data == null) {
                    len = sz;
                    data = tmp;
                } else {
                    byte[] narr;
                    int nlen;

                    nlen = len + sz;
                    narr = new byte[nlen];
                    System.arraycopy(data, 0, narr, 0, len);
                    System.arraycopy(tmp, 0, narr, len, sz);
                    data = narr;
                    len = nlen;
                }
            }
            if (len != data.length) {
                byte[] narr = new byte[len];

                System.arraycopy(data, 0, narr, 0, len);
                data = narr;
            }
            stmt = con.prepareStatement("INSERT INTO BlobTest(fileName, " + "blobData) VALUES(?, ?)");
            stmt.setString(1, args[0]);
            stmt.setObject(2, data);
            stmt.executeUpdate();
            f.delete();
        }
        con.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.l2jfree.loginserver.tools.L2GameServerRegistrar.java

/**
 * Launches the interactive game server registration.
 * //from  w  w  w.  j  a v  a2 s. com
 * @param args ignored
 */
public static void main(String[] args) {
    // LOW rework this crap
    Util.printSection("Game Server Registration");
    _log.info("Please choose:");
    _log.info("list - list registered game servers");
    _log.info("reg - register a game server");
    _log.info("rem - remove a registered game server");
    _log.info("hexid - generate a legacy hexid file");
    _log.info("quit - exit this application");

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    L2GameServerRegistrar reg = new L2GameServerRegistrar();

    String line;
    try {
        RegistrationState next = RegistrationState.INITIAL_CHOICE;
        while ((line = br.readLine()) != null) {
            line = line.trim().toLowerCase();
            switch (reg.getState()) {
            case GAMESERVER_ID:
                try {
                    int id = Integer.parseInt(line);
                    if (id < 1 || id > 127)
                        throw new IllegalArgumentException("ID must be in [1;127].");
                    reg.setId(id);
                    reg.setState(next);
                } catch (RuntimeException e) {
                    _log.info("You must input a number between 1 and 127");
                }

                if (reg.getState() == RegistrationState.ALLOW_BANS) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con
                                .prepareStatement("SELECT allowBans FROM gameserver WHERE id = ?");
                        ps.setInt(1, reg.getId());
                        ResultSet rs = ps.executeQuery();
                        if (rs.next()) {
                            _log.info("A game server is already registered on ID " + reg.getId());
                            reg.setState(RegistrationState.INITIAL_CHOICE);
                        } else
                            _log.info("Allow account bans from this game server? [y/n]:");
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not remove a game server!", e);
                    } finally {
                        L2Database.close(con);
                    }
                } else if (reg.getState() == RegistrationState.REMOVE) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con.prepareStatement("DELETE FROM gameserver WHERE id = ?");
                        ps.setInt(1, reg.getId());
                        int cnt = ps.executeUpdate();
                        if (cnt == 0)
                            _log.info("No game server registered on ID " + reg.getId());
                        else
                            _log.info("Game server removed.");
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not remove a game server!", e);
                    } finally {
                        L2Database.close(con);
                    }
                    reg.setState(RegistrationState.INITIAL_CHOICE);
                } else if (reg.getState() == RegistrationState.GENERATE) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con
                                .prepareStatement("SELECT authData FROM gameserver WHERE id = ?");
                        ps.setInt(1, reg.getId());
                        ResultSet rs = ps.executeQuery();

                        if (rs.next()) {
                            reg.setAuth(rs.getString("authData"));
                            byte[] b = HexUtil.hexStringToBytes(reg.getAuth());

                            Properties pro = new Properties();
                            pro.setProperty("ServerID", String.valueOf(reg.getId()));
                            pro.setProperty("HexID", HexUtil.hexToString(b));

                            BufferedOutputStream os = new BufferedOutputStream(
                                    new FileOutputStream("hexid.txt"));
                            pro.store(os, "the hexID to auth into login");
                            IOUtils.closeQuietly(os);
                            _log.info("hexid.txt has been generated.");
                        } else
                            _log.info("No game server registered on ID " + reg.getId());

                        rs.close();
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not generate hexid.txt!", e);
                    } finally {
                        L2Database.close(con);
                    }
                    reg.setState(RegistrationState.INITIAL_CHOICE);
                }
                break;
            case ALLOW_BANS:
                try {
                    if (line.length() != 1)
                        throw new IllegalArgumentException("One char required.");
                    else if (line.charAt(0) == 'y')
                        reg.setTrusted(true);
                    else if (line.charAt(0) == 'n')
                        reg.setTrusted(false);
                    else
                        throw new IllegalArgumentException("Invalid choice.");

                    byte[] auth = Rnd.nextBytes(new byte[BYTES]);
                    reg.setAuth(HexUtil.bytesToHexString(auth));

                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con.prepareStatement(
                                "INSERT INTO gameserver (id, authData, allowBans) VALUES (?, ?, ?)");
                        ps.setInt(1, reg.getId());
                        ps.setString(2, reg.getAuth());
                        ps.setBoolean(3, reg.isTrusted());
                        ps.executeUpdate();
                        ps.close();

                        _log.info("Registered game server on ID " + reg.getId());
                        _log.info("The authorization string is:");
                        _log.info(reg.getAuth());
                        _log.info("Use it when registering this login server.");
                        _log.info("If you need a legacy hexid file, use the 'hexid' command.");
                    } catch (SQLException e) {
                        _log.error("Could not register gameserver!", e);
                    } finally {
                        L2Database.close(con);
                    }

                    reg.setState(RegistrationState.INITIAL_CHOICE);
                } catch (IllegalArgumentException e) {
                    _log.info("[y/n]?");
                }
                break;
            default:
                if (line.equals("list")) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con.prepareStatement("SELECT id, allowBans FROM gameserver");
                        ResultSet rs = ps.executeQuery();
                        while (rs.next())
                            _log.info("ID: " + rs.getInt("id") + ", trusted: " + rs.getBoolean("allowBans"));
                        rs.close();
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not register gameserver!", e);
                    } finally {
                        L2Database.close(con);
                    }
                    reg.setState(RegistrationState.INITIAL_CHOICE);
                } else if (line.equals("reg")) {
                    _log.info("Enter the desired ID:");
                    reg.setState(RegistrationState.GAMESERVER_ID);
                    next = RegistrationState.ALLOW_BANS;
                } else if (line.equals("rem")) {
                    _log.info("Enter game server ID:");
                    reg.setState(RegistrationState.GAMESERVER_ID);
                    next = RegistrationState.REMOVE;
                } else if (line.equals("hexid")) {
                    _log.info("Enter game server ID:");
                    reg.setState(RegistrationState.GAMESERVER_ID);
                    next = RegistrationState.GENERATE;
                } else if (line.equals("quit"))
                    Shutdown.exit(TerminationStatus.MANUAL_SHUTDOWN);
                else
                    _log.info("Incorrect command.");
                break;
            }
        }
    } catch (IOException e) {
        _log.fatal("Could not process input!", e);
    } finally {
        IOUtils.closeQuietly(br);
    }
}

From source file:driver.ieSystem2.java

public static void main(String[] args) throws SQLException {

    Scanner sc = new Scanner(System.in);
    boolean login = false;
    int check = 0;
    int id = 0;/*from   w w w.  java2 s .c  o  m*/
    String user = "";
    String pass = "";
    Person person = null;
    Date day = null;

    JOptionPane.showMessageDialog(null, "WELCOME TO SYSTEM", "Starting Project",
            JOptionPane.INFORMATION_MESSAGE);
    do {
        System.out.println("What do you want?");
        System.out.println("press 1 : Login");
        System.out.println("press 2 : Create New User");
        System.out.println("Press 3 : Exit ");
        System.out.println("");
        do {
            try {
                System.out.print("Enter: ");
                check = sc.nextInt();
            } catch (InputMismatchException e) {
                JOptionPane.showMessageDialog(null, "Invalid Input", "Message", JOptionPane.WARNING_MESSAGE);
                sc.next();
            }
        } while (check <= 1 && check >= 3);

        // EXIT 
        if (check == 3) {
            System.out.println("Close Application");
            System.exit(0);
        }
        // CREATE USER
        if (check == 2) {
            System.out.println("-----------------------------------------");
            System.out.println("Create New User");
            System.out.println("-----------------------------------------");
            System.out.print("Account ID: ");
            id = sc.nextInt();
            System.out.print("Username: ");
            user = sc.next();
            System.out.print("Password: ");
            pass = sc.next();
            try {
                Person.createUser(id, user, pass, 0, 0, 0, 0, 0);
                System.out.println("-----------------------------------------");
                System.out.println("Create Complete");
                System.out.println("-----------------------------------------");
            } catch (Exception e) {
                System.out.println("-----------------------------------------");
                System.out.println("Error, Try again");
                System.out.println("-----------------------------------------");
            }
        } else if (check == 1) {
            // LOGIN
            do {
                System.out.println("-----------------------------------------");
                System.out.println("LOGIN ");
                System.out.print("Username: ");
                user = sc.next();
                System.out.print("Password: ");
                pass = sc.next();
                if (Person.checkUser(user, pass)) {
                    System.out.println("-----------------------------------------");
                    System.out.println("Login Complete");
                } else {
                    System.out.println("-----------------------------------------");
                    System.out.println("Invalid Username / Password");
                }
            } while (!Person.checkUser(user, pass));
        }
    } while (check != 1);
    login = true;

    person = new Person(user);
    do {
        System.out.println("-----------------------------------------");
        System.out.println("Hi " + person.getPerName());
        System.out.println("Press 1 : Add Income");
        System.out.println("Press 2 : Add Expense");
        System.out.println("Press 3 : Add Save");
        System.out.println("Press 4 : History");
        System.out.println("Press 5 : Search");
        System.out.println("Press 6 : Analytics");
        System.out.println("Press 7 : Total");
        System.out.println("Press 8 : All Summary");
        System.out.println("Press 9 : Sign Out");
        do {
            try {
                System.out.print("Enter : ");
                check = sc.nextInt();
            } catch (InputMismatchException e) {
                System.out.println("Invalid Input");
                sc.next();
            }
        } while (check <= 1 && check >= 5);
        // Add Income
        if (check == 1) {
            double Income;
            String catalog = "";
            double IncomeTotal = 0;
            catalog = JOptionPane.showInputDialog("What is your income : ");
            Income = Integer.parseInt(JOptionPane.showInputDialog("How much is it   "));

            person.addIncome(person.getPerId(), day, catalog, Income);
            person.update();
        } //Add Expense
        else if (check == 2) {
            double Expense;
            String catalog = "";
            catalog = JOptionPane.showInputDialog("What is your expense :");
            Expense = Integer.parseInt(JOptionPane.showInputDialog("How much is it   "));
            person.addExpense(person.getPerId(), day, catalog, Expense);
            person.update();
        } //Add Save 
        else if (check == 3) {
            double Saving;
            double SavingTotal = 0;
            String catalog = "";

            Saving = Integer.parseInt(JOptionPane.showInputDialog("How much is it "));
            SavingTotal += Saving;
            person.addSave(person.getPerId(), day, catalog, Saving);
            person.update();
        } //History
        else if (check == 4) {
            String x;
            do {
                System.out.println("-----------------------------------------");
                System.out.println("YOUR HISTORY");
                System.out.println("Date                Type           Amount");
                System.out.println("-----------------------------------------");
                List<History> history = person.getHistory();
                if (history != null) {
                    int count = 1;
                    for (History h : history) {
                        if (count++ <= 1) {
                            System.out.println(h.getHistoryDateTime() + "   " + h.getHistoryDescription()
                                    + "           " + h.getAmount());
                        } else {
                            System.out.println(h.getHistoryDateTime() + "   " + h.getHistoryDescription()
                                    + "           " + h.getAmount());
                        }
                    }
                }
                System.out.println("-----------------------------------------");
                System.out.print("Back to menu (0 or back) : ");
                x = sc.next();
            } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0"));
        } //Searh
        else if (check == 5) {
            try {
                Connection conn = ConnectionDB.getConnection();
                long a = person.getPerId();
                String NAME = "Salary";
                PreparedStatement ps = conn.prepareStatement(
                        "SELECT * FROM  INCOME WHERE PERID = " + a + "  and CATALOG LIKE '%" + NAME + "%' ");
                ResultSet rec = ps.executeQuery();

                while ((rec != null) && (rec.next())) {
                    System.out.print(rec.getDate("Days"));
                    System.out.print(" - ");
                    System.out.print(rec.getString("CATALOG"));
                    System.out.print(" - ");
                    System.out.print(rec.getDouble("AMOUNT"));
                    System.out.print(" - ");
                }
                ps.close();
                conn.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } //Analy 
        else if (check == 6) {
            String x;
            do {
                DecimalFormat df = new DecimalFormat("##.##");
                double in = person.getIncome();
                double ex = person.getExpense();
                double sum = person.getSumin_ex();
                System.out.println("-----------------------------------------");
                System.out.println("Income : " + df.format((in / sum) * 100) + "%");
                System.out.println("Expense : " + df.format((ex / sum) * 100) + "%");
                System.out.println("\n\n");
                System.out.print("Back to menu (0 or back) : ");
                x = sc.next();
            } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0"));
        } //TOTAL
        else if (check == 7) {
            String x;
            do {
                System.out.println("-----------------------------------------");
                System.out.println("TOTALSAVE             TOTAL");
                System.out.println(
                        person.getTotalSave() + " Baht" + "             " + person.getTotal() + " Baht");
                System.out.println("\n\n");
                System.out.print("Back to menu (0 or back) : ");
                x = sc.next();
            } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0"));
        } //ALL Summy
        else if (check == 8) {
            String x;
            do {
                DecimalFormat df = new DecimalFormat("##.##");
                double in = person.getIncome();
                double ex = person.getExpense();
                double sum = person.getSumin_ex();
                double a = ((in / sum) * 100);
                double b = ((ex / sum) * 100);
                System.out.println("-----------------------------------------");
                System.out.println("ALL SUMMARY");
                System.out.println("Account: " + person.getPerName());
                System.out.println("");
                System.out.println("Total Save ------------- Total");
                System.out
                        .println(person.getTotalSave() + " Baht               " + person.getTotal() + " Baht");
                System.out.println("");

                System.out.println("INCOME --------------- EXPENSE");
                System.out.println(df.format(a) + "%" + "                  " + df.format(b) + "%");

                System.out.println("-----------------------------------------");
                System.out.println("\n\n");
                System.out.print("Back to menu (0 or back) : ");
                x = sc.next();
            } while (!x.equalsIgnoreCase("back") && !x.equalsIgnoreCase("0"));
        } //LOG OUT 
        else {
            System.out.println("See ya.\n");
            login = false;
            break;
        }
    } while (true);
}

From source file:ca.uwaterloo.iss4e.algorithm.PARX.java

public static void main(String[] args) {

    String url = "jdbc:postgresql://localhost/essex";
    Properties props = new Properties();
    props.setProperty("user", "xiliu");
    props.setProperty("password", "Abcd1234");

    try {/*  w  ww  . jav a  2s  .  c o m*/
        /* Random generator = new Random();
         BigDecimal[] d = new BigDecimal[40];
         for (int i=0; i<40; ++i){
        d[i] = new BigDecimal(generator.nextInt(10));
        System.out.print(d[i].doubleValue()+"("+i+") |");
         }
         System.out.println("\n ---------------");
         Pair<double[], double[][]> values = PARX.prepareVariable(d, 11, 12, 2, 4);
         double[] Y = values.getKey();
         double X[][] = values.getValue();
         for (int i=0; i<Y.length; ++i){
                
        for (int j=0; j<X[i].length; ++j) {
            System.out.print(X[i][j] + " |");
        }
        System.out.print("|" +Y[i]);
        System.out.println();
         }
        */

        Class.forName("org.postgresql.Driver");
        Connection conn = DriverManager.getConnection(url, props);
        PreparedStatement pstmt = conn.prepareStatement(
                "select array_agg(A.reading) from (select reading from meterreading where homeid=? and readdate between ? and ? order by readdate desc, readtime desc) A ");
        pstmt.setInt(1, 19419);
        pstmt.setDate(2, java.sql.Date.valueOf("2011-04-03"));
        pstmt.setDate(3, java.sql.Date.valueOf("2011-09-07"));

        ResultSet rs = pstmt.executeQuery();

        int order = 3;

        int numOfSeasons = 24;
        int intervalOfUpdateModel = 4; //Every four hours
        int startPredict = 6 * 24;
        int numOfPointsForTraining = 24 * 5;
        double[] pointsForPredict = new double[order];

        if (rs.next()) {
            BigDecimal[] readings = (BigDecimal[]) (rs.getArray(1).getArray());
            double[][] data = new double[2][readings.length + 1];
            int i = 0;
            for (; i < startPredict; ++i) {
                data[0][i] = readings[i].doubleValue();
                data[1][i] = 0.0;
            }

            double[] beta = null;
            int updateModelCount = 0;
            for (; i < readings.length; ++i) {
                // if (updateModelCount%intervalOfUpdateModel==0) {
                // beta = PARX.computePARModel(readings, i, i+1, order, numOfSeasons);
                ++updateModelCount;
                //}
                for (int p = 0; p < order; ++p) {
                    pointsForPredict[order - 1 - p] = readings[i - p].doubleValue();
                }
                data[0][i] = readings[i].doubleValue();
                //   data[1][i+1] = PARX.predict(pointsForPredict, order, beta);
            }

            for (int j = 0; j < readings.length + 1; ++j) {
                System.out.println(data[0][j] + ", " + data[1][j]);
            }

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

From source file:de.tudarmstadt.ukp.csniper.resbuild.EvaluationItemFixer2.java

public static void main(String[] args) {
    connect(HOST, DATABASE, USER, PASSWORD);

    Map<Integer, String> items = new HashMap<Integer, String>();
    Map<Integer, String> failed = new HashMap<Integer, String>();

    // fetch coveredTexts of dubious items and clean it
    PreparedStatement select = null;
    PreparedStatement update = null;
    try {/*from  w  w w  . j a v  a2s .c  o m*/
        StringBuilder selectQuery = new StringBuilder();
        selectQuery.append("SELECT * FROM cachedparse WHERE pennTree = 'ERROR' OR pennTree = ''");

        select = connection.prepareStatement(selectQuery.toString());
        log.info("Running query [" + selectQuery.toString() + "].");
        ResultSet rs = select.executeQuery();

        //         CSVWriter writer;
        String text;
        JCas jcas = JCasFactory.createJCas();
        String updateQuery = "UPDATE CachedParse SET pennTree = ? WHERE collectionId = ? AND documentId = ? AND beginOffset = ? AND endOffset = ?";
        update = connection.prepareStatement(updateQuery);
        //         File base = new File("");

        AnalysisEngine sentences = createEngine(DummySentenceSplitter.class);
        AnalysisEngine tokenizer = createEngine(StanfordSegmenter.class,
                StanfordSegmenter.PARAM_CREATE_SENTENCES, false, StanfordSegmenter.PARAM_CREATE_TOKENS, true);
        AnalysisEngine parser = createEngine(StanfordParser.class, StanfordParser.PARAM_WRITE_CONSTITUENT, true,
                //               StanfordParser.PARAM_CREATE_DEPENDENCY_TAGS, true,
                StanfordParser.PARAM_WRITE_PENN_TREE, true, StanfordParser.PARAM_LANGUAGE, "en",
                StanfordParser.PARAM_VARIANT, "factored");

        while (rs.next()) {
            String collectionId = rs.getString("collectionId");
            String documentId = rs.getString("documentId");
            int beginOffset = rs.getInt("beginOffset");
            int endOffset = rs.getInt("endOffset");
            text = retrieveCoveredText(collectionId, documentId, beginOffset, endOffset);

            jcas.setDocumentText(text);
            jcas.setDocumentLanguage("en");
            sentences.process(jcas);
            tokenizer.process(jcas);
            parser.process(jcas);

            //            writer = new CSVWriter(new FileWriter(new File(base, documentId + ".csv"));

            System.out.println("Updating " + text);
            for (PennTree p : JCasUtil.select(jcas, PennTree.class)) {
                String tree = StringUtils.normalizeSpace(p.getPennTree());
                update.setString(1, tree);
                update.setString(2, collectionId);
                update.setString(3, documentId);
                update.setInt(4, beginOffset);
                update.setInt(5, endOffset);
                update.executeUpdate();
                System.out.println("with tree " + tree);
                break;
            }
            jcas.reset();
        }
    } catch (SQLException e) {
        log.error("Exception while selecting: " + e.getMessage());
    } catch (UIMAException e) {
        e.printStackTrace();
    } finally {
        closeQuietly(select);
        closeQuietly(update);
    }

    // write logs
    //      BufferedWriter bwf = null;
    //      BufferedWriter bws = null;
    //      try {
    //         bwf = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(
    //               LOG_FAILED)), "UTF-8"));
    //         for (Entry<Integer, String> e : failed.entrySet()) {
    //            bwf.write(e.getKey() + " - " + e.getValue() + "\n");
    //         }
    //
    //         bws = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(
    //               LOG_SUCCESSFUL)), "UTF-8"));
    //         for (Entry<Integer, String> e : items.entrySet()) {
    //            bws.write(e.getKey() + " - " + e.getValue() + "\n");
    //         }
    //      }
    //      catch (IOException e) {
    //         log.error("Got an IOException while writing the log files.");
    //      }
    //      finally {
    //         IOUtils.closeQuietly(bwf);
    //         IOUtils.closeQuietly(bws);
    //      }

    log.info("Texts for [" + items.size() + "] items need to be cleaned up.");

    // update the dubious items with the cleaned coveredText
    //      PreparedStatement update = null;
    //      try {
    //         String updateQuery = "UPDATE EvaluationItem SET coveredText = ? WHERE id = ?";
    //
    //         update = connection.prepareStatement(updateQuery);
    //         int i = 0;
    //         for (Entry<Integer, String> e : items.entrySet()) {
    //            int id = e.getKey();
    //            String coveredText = e.getValue();
    //
    //            // update item in database
    //            update.setString(1, coveredText);
    //            update.setInt(2, id);
    //            update.executeUpdate();
    //            log.debug("Updating " + id + " with [" + coveredText + "]");
    //
    //            // show percentage of updated items
    //            i++;
    //            int part = (int) Math.ceil((double) items.size() / 100);
    //            if (i % part == 0) {
    //               log.info(i / part + "% finished (" + i + "/" + items.size() + ").");
    //            }
    //         }
    //      }
    //      catch (SQLException e) {
    //         log.error("Exception while updating: " + e.getMessage());
    //      }
    //      finally {
    //         closeQuietly(update);
    //      }

    closeQuietly(connection);
}