Example usage for java.sql ResultSet getDate

List of usage examples for java.sql ResultSet getDate

Introduction

In this page you can find the example usage for java.sql ResultSet getDate.

Prototype

java.sql.Date getDate(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a java.sql.Date object in the Java programming language.

Usage

From source file:com.spvp.dal.MySqlDatabase.java

private void osvjeziHistorijuPrognozaZaGrad(Grad g, WebService ws) {

    try (Connection conn = getConnection()) {

        PreparedStatement ps = conn.prepareStatement("SELECT hp.datum dat "
                + "FROM historija_prognoze hp, gradovi_prognoze gp "
                + "WHERE hp.id = gp.prognoza_id AND gp.grad_id = ? " + "ORDER BY hp.datum DESC " + "LIMIT 1");

        ps.setInt(1, g.getIdGrada());// w w w. jav  a  2s. c  o m

        ResultSet rs = ps.executeQuery();

        if (rs.next()) {

            Calendar cal = Calendar.getInstance();
            cal.setTime(rs.getDate("dat"));
            cal.set(Calendar.MILLISECOND, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.HOUR, 0);

            //System.out.println("Zadnji datum u bazi je bio: " + cal.getTime().toString());

            Calendar tempDate = Calendar.getInstance();
            tempDate.set(Calendar.MILLISECOND, 0);
            tempDate.set(Calendar.SECOND, 0);
            tempDate.set(Calendar.MINUTE, 0);
            tempDate.set(Calendar.HOUR, 0);

            //System.out.println("Danasnji datum je: " + tempDate.getTime().toString());

            long diff = tempDate.getTime().getTime() - cal.getTime().getTime();
            long brDana = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);

            //System.out.println("Razlika u danima je: " + brDana);

            if (brDana == 0)
                return;

            //System.out.println("Osvjezavanje zadnjeg dana u bazi...");

            this.osvjeziZadnjuPrognozuZaGrad(g, ws);

            //System.out.println("Ucitavanje novih prognoza...");

            Location l = new Location(false);
            l.setCity(g.getImeGrada());
            l.setCountry("Bosnia and Herzegovina");
            l.setCountryCode("ba");
            l.setLatitude(g.getLatitude());
            l.setLongitude(g.getLongitude());
            l.setStatus(Boolean.TRUE);

            this.ucitajPrognozeUBazu(ws.getHistorijskePodatkeByLocation(l, (int) brDana));

        } else { // Ne postoji ni jedan unos prognoze za dati grad

            //System.out.println("Zadnji datum u bazi je bio: " + rs.getDate("dat").toString());

            Location l = new Location(true);
            l.setCity(g.getImeGrada());
            l.setCountryCode("ba");
            l.setLatitude(g.getLatitude());
            l.setLongitude(g.getLongitude());
            l.setCountry("Bosnia and Herzegovina");

            this.ucitajPrognozeUBazu(ws.getHistorijskePodatkeByLocation(l, 15));

        }

    } catch (SQLException ex) {
        Logger.getLogger(MySqlDatabase.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(MySqlDatabase.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:Statement.Statement.java

private void loadExpense() {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_YEAR, 1);
    Date tomorrow = calendar.getTime();
    dateFormat.format(tomorrow);// w w  w.  jav a  2 s.c o  m

    evaluator = new HighlightEvaluator();
    evaluator.setStartDate(tomorrow);

    try {
        PreparedStatement st = cnn.prepareStatement("SELECT Date FROM Expense where ShopID = ?");
        st.setString(1, code);
        ResultSet rs = st.executeQuery();

        while (rs.next()) {

            evaluator.add(rs.getDate(1));
        }

    } catch (Exception e) {
    }
    jc.getDayChooser().addDateEvaluator(evaluator);
    jc.setCalendar(jc.getCalendar());
}

From source file:Statement.Statement.java

private void loadRevenue() {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_YEAR, 1);
    Date tomorrow = calendar.getTime();
    dateFormat.format(tomorrow);// ww w.  j a va2  s.c  o m

    evaluator = new HighlightEvaluator();
    evaluator.setStartDate(tomorrow);

    try {
        PreparedStatement st = cnn.prepareStatement("SELECT Date FROM Revenue where ShopID = ?");
        st.setString(1, code);
        ResultSet rs = st.executeQuery();

        while (rs.next()) {

            evaluator.add(rs.getDate(1));
        }

    } catch (Exception e) {
    }
    jc.getDayChooser().addDateEvaluator(evaluator);
    jc.setCalendar(jc.getCalendar());
}

From source file:com.chariotsolutions.crowd.connector.PrincipalRowMapper.java

public RemotePrincipal mapRow(ResultSet rs, int i) throws SQLException {

    long id = rs.getLong("id");
    String username = rs.getString("user_name");
    String email = rs.getString("email");
    String firstName = rs.getString("first_name");
    String lastName = rs.getString("last_name");
    String company = rs.getString("company");
    String title = rs.getString("title");
    String phone = rs.getString("phone");
    String country = rs.getString("country");

    String password = rs.getString("password");
    PasswordCredential credential = new PasswordCredential(password, true);

    boolean active = !rs.getBoolean("account_disabled");
    Date created = rs.getDate("created");

    RemotePrincipal principal = new RemotePrincipal();

    principal.setID(id);/* ww w  .  java 2  s  . c  om*/
    principal.setName(username);
    principal.setEmail(email);
    principal.setActive(active);
    principal.setAttribute(RemotePrincipal.FIRSTNAME, firstName);
    principal.setAttribute(RemotePrincipal.LASTNAME, lastName);
    principal.setAttribute(RemotePrincipal.DISPLAYNAME, firstName + " " + lastName);

    principal.setAttribute("company", company);
    principal.setAttribute("title", title);
    principal.setAttribute("phone", phone);
    principal.setAttribute("country", country);

    principal.setConception(created);

    principal.setCredentials(Collections.singletonList(credential));
    principal.setCredentialHistory(Collections.singletonList(credential));

    return principal;
}

From source file:CatalogWSModel.CatalogWS.java

@WebMethod(operationName = "searchProduct")
public ArrayList searchProduct(@WebParam(name = "keyword") String keyword,
        @WebParam(name = "filter") String filter, @WebParam(name = "user_id") String user_id) {
    ArrayList<String> answers = new ArrayList<String>();
    Connection dbConn = DbConnectionManager.getConnection();
    try {//from www. j  a  va 2s. c o  m
        String query;
        if (filter.equals("product")) {
            query = "SELECT * FROM catalogue WHERE productname like '%" + keyword + "%'";
        } else {
            query = "SELECT * FROM catalogue WHERE username like '%" + keyword + "%'";
        }

        Statement ps = dbConn.createStatement();
        ResultSet rs = ps.executeQuery(query);
        while (rs.next()) {
            String productname = rs.getString("productname");
            int product_id = rs.getInt("product_id");
            int price = rs.getInt("price");
            String seller = rs.getString("username");
            String productdesc = rs.getString("productdesc");
            Date dateAddedF = rs.getDate("dateadded");
            SimpleDateFormat simpledatafo = new SimpleDateFormat("dd/MM/yyyy");
            Time timeAddedF = rs.getTime("timeadded");
            SimpleDateFormat simpletimefo = new SimpleDateFormat("dd/MM/yyyy");
            String dateadded = rs.getString("dateadded");
            String timeadded = rs.getString("timeadded");
            String qLike = "SELECT * from likes WHERE product_id='" + product_id + "'";
            Statement psLike = dbConn.createStatement();
            ResultSet rsLike = psLike.executeQuery(qLike);
            int count = 0;
            while (rsLike.next()) {
                count++;
            }
            int likes = count;
            int purchases = rs.getInt("purchases");
            String imagepath = rs.getString("imagepath");

            String statuslike = "<span><a id=\"like\" href=\"like?product_id=" + product_id
                    + "\"><b>LIKE</b></a></span>";
            String checkLike = "SELECT * from likes WHERE product_id='" + product_id + "' AND user_id='"
                    + user_id + "'";
            Statement psCheckLike = dbConn.createStatement();
            ResultSet rsCheckLike = psLike.executeQuery(checkLike);
            count = 0;
            boolean hasLiked = rsCheckLike.next();
            if (!hasLiked) {
                statuslike = "<span><a id=\"like\" href=\"like?product_id=" + product_id
                        + "\"><b>LIKE</b></a></span>";
            } else {
                statuslike = "<span><a id=\"dislike\" href=\"dislike?product_id=" + product_id
                        + "\"><b>LIKED</b></a></span>";
            }

            String answer = "<li>" + "<span id='date'>" + "<b>" + seller + "</b>" + "</span><br/>"
                    + "<span id='date'>" + dateadded + "<br/>" + "at " + timeadded + "<hr></hr>" + "</span>"
                    + "<div class='item-list-product'>" + "<div style='position:absolute'>" + "<a href='"
                    + imagepath + "'><img class='img-item' src='" + imagepath + "'></img></a>" + "</div>"
                    + "<div id='product-info'>" + "<span><b>" + productname + "</b></span> <br/>" + "<span>IDR "
                    + price + "</span> <br/>" + "<span style='font-size:12px;position:relative'>" + productdesc
                    + "</span>" + "</div>" + "<div id='eddel'>" + "<br/>" + "<span style='font-size:14px'>"
                    + likes + " likes</span> <br/>" + "<span style='font-size:14px'>" + purchases
                    + " purchase</span> <br/>" + "<br/>" + statuslike
                    + "<span style='margin-left:10px'><a id='buy' href='confirm.jsp?product_id=" + product_id
                    + "'><b>    BUY </b></a> </span>" + "</div>" + "</div>" + "</li>" + "<br/><br/>";
            answers.add(answer);

        }
    } catch (SQLException ex) {
        System.out.println("Insert to database failed: An Exception has occurred! " + ex);
    }

    return answers;
}

From source file:jeeves.resources.dbms.Dbms.java

private Element buildElement(ResultSet rs, int col, String name, int type, Hashtable<String, String> formats)
        throws SQLException {
    String value = null;//from   ww w  .j  av a2  s.  c o m

    switch (type) {
    case Types.DATE:
        Date date = rs.getDate(col + 1);
        if (date == null)
            value = null;
        else {
            String format = formats.get(name);
            SimpleDateFormat df = (format == null) ? new SimpleDateFormat(DEFAULT_DATE_FORMAT)
                    : new SimpleDateFormat(format);
            value = df.format(date);
        }
        break;

    case Types.TIME:
        Time time = rs.getTime(col + 1);
        if (time == null)
            value = null;
        else {
            String format = formats.get(name);
            SimpleDateFormat df = (format == null) ? new SimpleDateFormat(DEFAULT_TIME_FORMAT)
                    : new SimpleDateFormat(format);
            value = df.format(time);
        }
        break;

    case Types.TIMESTAMP:
        Timestamp timestamp = rs.getTimestamp(col + 1);
        if (timestamp == null)
            value = null;
        else {
            String format = formats.get(name);
            SimpleDateFormat df = (format == null) ? new SimpleDateFormat(DEFAULT_TIMESTAMP_FORMAT)
                    : new SimpleDateFormat(format);
            value = df.format(timestamp);
        }
        break;

    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
    case Types.BIGINT:
        long l = rs.getLong(col + 1);
        if (rs.wasNull())
            value = null;
        else {
            String format = formats.get(name);
            if (format == null)
                value = l + "";
            else {
                DecimalFormat df = new DecimalFormat(format);
                value = df.format(l);
            }
        }
        break;

    case Types.DECIMAL:
    case Types.FLOAT:
    case Types.DOUBLE:
    case Types.REAL:
    case Types.NUMERIC:
        double n = rs.getDouble(col + 1);

        if (rs.wasNull())
            value = null;
        else {
            String format = formats.get(name);

            if (format == null) {
                value = n + "";

                // --- this fix is mandatory for oracle
                // --- that shit returns integers like xxx.0

                if (value.endsWith(".0"))
                    value = value.substring(0, value.length() - 2);
            } else {
                DecimalFormat df = new DecimalFormat(format);
                value = df.format(n);
            }
        }
        break;

    default:
        value = rs.getString(col + 1);
        if (value != null) {
            value = stripIllegalChars(value);
        }

        break;
    }
    return new Element(name).setText(value);
}

From source file:org.apache.torque.generated.peer.DefaultValuesFromDatabaseTest.java

private Date doSelect(String toSelect, Class<?> classToSelect) throws Exception {
    String sql;/*w  w w .  j  ava2  s.co m*/
    if (defaultAdapter instanceof OracleAdapter) {
        sql = "select " + toSelect + " from dual";
    } else if (defaultAdapter instanceof DerbyAdapter) {
        sql = "values(" + toSelect + ")";
    } else if (defaultAdapter instanceof HsqldbAdapter) {
        sql = "call " + toSelect;
    } else if (defaultAdapter instanceof MssqlAdapter) {
        sql = "select convert(datetime," + toSelect + ")";
    } else {
        sql = "select " + toSelect;
    }
    Connection connection = null;
    try {
        connection = Torque.getConnection();
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
        if (!resultSet.next()) {
            fail("Statement " + sql + " returned 0 rows");
        }
        Date result;
        if (Time.class == classToSelect) {
            result = resultSet.getTime(1);
        } else if (java.sql.Date.class == classToSelect) {
            result = resultSet.getDate(1);
        } else if (Timestamp.class == classToSelect) {
            result = resultSet.getTimestamp(1);
        } else {
            throw new IllegalArgumentException("unknown classToSelect " + classToSelect.getName());
        }
        if (resultSet.next()) {
            fail("Statement " + sql + " returned more than 1 row");
        }
        return result;
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
                // ignore
            }
        }
    }
}

From source file:com.havoc.hotel.admin.dao.impl.UserDAOImpl.java

@Override
public User getById(int userId) throws SQLException {
    return (User) jdbcTemplate.query(SQLConstant.USER_GETById, new Object[] { userId },
            new ResultSetExtractor<User>() {

                @Override/*from   w  w w  .  j  av a2  s  .  co  m*/
                public User extractData(ResultSet rs) throws SQLException, DataAccessException {
                    User u = null;
                    if (rs.next()) {
                        u = new User();
                        u.setUserId(rs.getInt("user_id"));
                        u.setFirstName(rs.getString("first_name"));
                        u.setLastName(rs.getString("last_name"));
                        u.setEmail(rs.getString("email"));
                        u.setUsername(rs.getString("username"));
                        u.setPassword(rs.getString("password"));
                        u.setRoleId(rs.getInt("role_id"));
                        u.setAddedDate(rs.getDate("added_date"));
                        u.setStatus(rs.getBoolean("status"));
                    }
                    return u;
                }
            });
}

From source file:com.havoc.hotel.admin.dao.impl.UserDAOImpl.java

@Override
public User authenticate(String username, String password) {
    return (User) jdbcTemplate.query(SQLConstant.USER_AUTHENTICATE, new Object[] { username, password },
            new ResultSetExtractor<User>() {

                @Override/*from  w w w . ja  v a  2s  .c  o  m*/
                public User extractData(ResultSet rs) throws SQLException, DataAccessException {
                    User u = null;
                    if (rs.next()) {
                        u = new User();
                        u.setUserId(rs.getInt("user_id"));
                        u.setFirstName(rs.getString("first_name"));
                        u.setLastName(rs.getString("last_name"));
                        u.setEmail(rs.getString("email"));
                        u.setUsername(rs.getString("username"));
                        u.setPassword(rs.getString("password"));
                        u.setRoleId(rs.getInt("role_id"));
                        u.setAddedDate(rs.getDate("added_date"));
                        u.setStatus(rs.getBoolean("status"));
                    }
                    return u;
                }
            });
}

From source file:com.spvp.dal.MySqlDatabase.java

@Override
public void osvjeziZadnjuPrognozuZaGrad(Grad grad, WebService ws) throws SQLException, ParseException {

    int id = grad.getIdGrada();

    try (Connection conn = getConnection()) {

        PreparedStatement ps = conn.prepareStatement(
                "SELECT hp.id id, hp.datum datum " + "FROM historija_prognoze hp, gradovi_prognoze gp "
                        + "WHERE hp.id = gp.prognoza_id AND gp.grad_id = ? AND hp.datum =(SELECT thp.datum "
                        + "FROM historija_prognoze thp, gradovi_prognoze tgp "
                        + "WHERE thp.id = tgp.prognoza_id AND tgp.grad_id = ? " + "ORDER BY thp.datum DESC "
                        + "LIMIT 1 " + ")");

        ps.setInt(1, id);//from ww w.  j  a va2s  . co m
        ps.setInt(2, id);

        ResultSet rs = ps.executeQuery();
        int idPrognoze = -1;
        Calendar cal = null;
        if (rs.next()) {
            idPrognoze = rs.getInt("id");
            cal = Calendar.getInstance();
            cal.setTime(rs.getDate("datum"));
        } else
            return;

        Location l = new Location(true);
        l.setCity(grad.getImeGrada());
        l.setCountry("Bosnia");
        l.setCountryCode("ba");
        l.setLatitude(grad.getLatitude());
        l.setLongitude(grad.getLongitude());

        //System.out.println(l.getCity());

        Prognoza prognoza = ws.getHistorijskePodatkeByLocationOnSpecificDate(l, cal);

        ps = conn.prepareStatement(
                "UPDATE historija_prognoze " + "SET vrijeme = ?, " + "    temp = ?, " + "    pritisak = ?, "
                        + "    brzina_vjetra = ?, " + "    vlaznost_zraka = ? " + "WHERE id = ?");

        ps.setString(1, prognoza.getVrijeme());
        ps.setString(2, prognoza.getTemperatura());
        ps.setString(3, prognoza.getPritisakZraka());
        ps.setString(4, prognoza.getBrzinaVjetra());
        ps.setString(5, prognoza.getVlaznostZraka());
        ps.setInt(6, idPrognoze);

        ps.executeUpdate();

        ps.close();
        conn.close();
        rs.close();

    }
}