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:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement st = conn.createStatement();

    st.executeUpdate("create table survey (id int,myDate DATE );");
    String INSERT_RECORD = "insert into survey(id, myDate) values(?, ?)";

    PreparedStatement pstmt = conn.prepareStatement(INSERT_RECORD);
    pstmt.setString(1, "1");
    java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
    pstmt.setDate(2, sqlDate);//from  w  w  w.ja v  a2 s .  c  o  m

    pstmt.executeUpdate();

    ResultSet rs = st.executeQuery("SELECT * FROM survey");

    while (rs.next()) {
        System.out.print(rs.getDate(2));
    }

    rs.close();
    st.close();
    conn.close();
}

From source file:GetDateFromOracle.java

public static void main(String args[]) {
    String GET_RECORD = "select date_column, time_column, " + "timestamp_column from TestDates where id = ?";
    ResultSet rs = null;
    Connection conn = null;// ww w.j  a v  a  2 s  .com
    PreparedStatement pstmt = null;
    try {
        conn = getConnection();
        pstmt = conn.prepareStatement(GET_RECORD);
        pstmt.setString(1, "0001");
        rs = pstmt.executeQuery();
        while (rs.next()) {
            java.sql.Date dbSqlDate = rs.getDate(1);
            java.sql.Time dbSqlTime = rs.getTime(2);
            java.sql.Timestamp dbSqlTimestamp = rs.getTimestamp(3);
            System.out.println("dbSqlDate=" + dbSqlDate);
            System.out.println("dbSqlTime=" + dbSqlTime);
            System.out.println("dbSqlTimestamp=" + dbSqlTimestamp);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            rs.close();
            pstmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:ex4.java

public static void main(String[] params) {
    CommandLine commandLine = null;//w  w w .  j  ava  2 s .  c  o m
    String sqlpath = "", host = "", port = "3306", username = "", password = "", database = "";
    Boolean query = false;
    Option option_sql = Option.builder("s").argName("sql").hasArg()
            .desc("Path to a file containing a valid MySQL sql statement").build();
    Option option_hostname = Option.builder("h").argName("host").hasArg().desc("ClearDB MySQL Hostname")
            .build();
    Option option_port = Option.builder("n").argName("port").hasArg().desc("ClearDB MySQL Port").build();
    Option option_username = Option.builder("u").argName("username").hasArg().desc("ClearDB MySQL Username")
            .build();
    Option option_password = Option.builder("p").argName("password").hasArg().desc("ClearDB MySQL Password")
            .build();
    Option option_dbname = Option.builder("d").argName("dbname").hasArg().desc("ClearDB MySQL Database Name")
            .build();
    Option option_help = Option.builder("w").argName("wanthelp").hasArg().desc("Help").build();
    Option option_query = Option.builder().longOpt("query").desc("Query type SQL Statement").build();
    Options options = new Options();
    CommandLineParser parser = new DefaultParser();

    options.addOption(option_sql);
    options.addOption(option_hostname);
    options.addOption(option_port);
    options.addOption(option_username);
    options.addOption(option_password);
    options.addOption(option_dbname);
    options.addOption(option_query);
    options.addOption(option_help);

    try {
        commandLine = parser.parse(options, params);
    } catch (MissingOptionException e) {
        help(options);
    } catch (MissingArgumentException e) {
        help(options);
    } catch (ParseException e) {
        System.out.println(e);
    }

    if (commandLine.hasOption("w") || params.length == 0) {
        help(options);
    }

    if (commandLine.hasOption("s")) {
        sqlpath = commandLine.getOptionValue("s");
    } else {
        System.out.println("Missing path to a SQL statement file");
        help(options);
    }
    if (commandLine.hasOption("h")) {
        host = commandLine.getOptionValue("h");
    } else {
        System.out.println("Missing ClearDB hostname (e.g. us-cdbr-iron-east-??.cleardb.net)");
        help(options);
    }
    if (commandLine.hasOption("n")) {
        port = commandLine.getOptionValue("n");
    } else {
        System.out.println("Missing ClearDB Port Value.  Defaulting to 3306");
    }
    if (commandLine.hasOption("u")) {
        username = commandLine.getOptionValue("u");
    } else {
        System.out.println("Missing ClearDB Username");
        help(options);
    }
    if (commandLine.hasOption("p")) {
        password = commandLine.getOptionValue("p");
    } else {
        System.out.println("Missing ClearDB Password");
        help(options);
    }
    if (commandLine.hasOption("d")) {
        database = commandLine.getOptionValue("d");
    } else {
        System.out.println("Missing ClearDB Database Name");
        help(options);
    }

    if (commandLine.hasOption("query")) {
        query = true;
    }

    String connectionURL = new StringBuilder().append("jdbc:mysql://").append(host).append(":").append(port)
            .append("/").append(database).append("?reconnect=true").toString();

    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        System.out.println(e);
    }

    try {
        Connection con = DriverManager.getConnection(connectionURL, username, password);
        Statement stmt = con.createStatement();
        if (query) {
            System.out.println("Querying target MySQL DB ...");
            ResultSet rs = stmt.executeQuery(readFile(sqlpath, Charset.defaultCharset()));
            while (rs.next())
                System.out.println(rs.getInt("emp_no") + "  " + rs.getDate("birth_date") + "  "
                        + rs.getString("first_name") + "  " + rs.getString("last_name") + "  "
                        + rs.getString("gender") + "  " + rs.getDate("hire_date"));
        } else {
            System.out.println("Updating target MySQL DB ...");
            int result = stmt.executeUpdate(readFile(sqlpath, Charset.defaultCharset()));
            System.out.println(result);
        }
        con.close();
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:GetDateFromMySql.java

public static void main(String args[]) {
    ResultSet rs = null;
    Connection conn = null;// www  . j a va  2  s  .c  om
    Statement stmt = null;
    try {
        conn = getMySQLConnection();
        stmt = conn.createStatement();
        rs = stmt.executeQuery("select timeCol, dateCol, dateTimeCol from dateTimeTable");
        while (rs.next()) {
            java.sql.Time dbSqlTime = rs.getTime(1);
            java.sql.Date dbSqlDate = rs.getDate(2);
            java.sql.Timestamp dbSqlTimestamp = rs.getTimestamp(3);
            System.out.println("dbSqlTime=" + dbSqlTime);
            System.out.println("dbSqlDate=" + dbSqlDate);
            System.out.println("dbSqlTimestamp=" + dbSqlTimestamp);

            java.util.Date dbSqlTimeConverted = new java.util.Date(dbSqlTime.getTime());
            java.util.Date dbSqlDateConverted = new java.util.Date(dbSqlDate.getTime());
            System.out.println("in standard date");
            System.out.println(dbSqlTimeConverted);
            System.out.println(dbSqlDateConverted);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

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;/* w ww  . j a  va2s.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:ExecuteMethod.java

public static void processExecute(Statement stmt, boolean executeResult) throws SQLException {
    if (!executeResult) {
        int updateCount = stmt.getUpdateCount();
        System.out.println(updateCount + " row was " + "inserted into Employee table.");

    } else {/*from   www.  jav a2  s . c o  m*/
        ResultSet rs = stmt.getResultSet();
        while (rs.next()) {
            System.out.println(rs.getInt("SSN") + rs.getString("Name") + rs.getDouble("Salary")
                    + rs.getDate("Hiredate") + rs.getInt("Loc_id"));

        }
    }
}

From source file:com.acme.spring.jdbc.JdbcTestHelper.java

/**
 * <p>Retrieves all the stocks from database, using passed {@link JdbcTemplate}.</p>
 *
 * @param jdbcTemplate the jdbc template to use
 *
 * @return list of stocks retrieved from database
 *//*from   w w  w.  j  av  a2  s.  co  m*/
public static List<Stock> retrieveAllStocks(JdbcTemplate jdbcTemplate) {

    return jdbcTemplate.query("select id, name, symbol, value, date from Stock order by name",
            new RowMapper<Stock>() {
                public Stock mapRow(ResultSet rs, int rowNum) throws SQLException {

                    int index = 1;

                    Stock result = new Stock();
                    result.setId(rs.getLong(index++));
                    result.setName(rs.getString(index++));
                    result.setSymbol(rs.getString(index++));
                    result.setValue(rs.getBigDecimal(index++));
                    result.setDate(rs.getDate(index++));

                    return result;
                }
            });
}

From source file:RSMetaData.java

public static void getData(ResultSet rs, int type, int colIdx) throws SQLException {
    switch (type) {
    case java.sql.Types.CHAR:
    case java.sql.Types.VARCHAR:
        System.out.println(rs.getString(colIdx));
        break;//  w w  w  .j a v a  2 s  .  c o m

    case java.sql.Types.INTEGER:
        int i = rs.getInt(colIdx);
        System.out.println(i);
        break;

    case java.sql.Types.NUMERIC:
        BigDecimal bd = rs.getBigDecimal(colIdx);
        System.out.println(bd.toString());
        break;

    case java.sql.Types.TIMESTAMP:
    case java.sql.Types.DATE:
        java.sql.Date d = rs.getDate(colIdx);
        System.out.println(d.toString());
        break;

    }
}

From source file:com.useekm.indexing.postgis.IndexedStatement.java

private static IndexedStatement convert(ResultSet results) throws SQLException {
    IndexedStatement result = new IndexedStatement();
    int idx = 1;/*ww  w.  ja  v a 2 s  .  c  om*/
    result.objectDate = results.getDate(idx++);
    result.objectLanguage = results.getString(idx++);
    result.objectSpatial = (PGgeometry) results.getObject(idx++);
    result.objectString = results.getString(idx++);
    result.objectTsVectorConfig = results.getString(idx++);
    result.objectType = results.getString(idx++);
    result.objectUri = results.getBoolean(idx++);
    result.predicate = results.getString(idx++);
    result.subject = results.getString(idx++);
    return result;
}

From source file:jongo.handler.JongoResultSetHandler.java

/**
 * Converts a ResultSet to a Map. Important to note that DATE, TIMESTAMP & TIME objects generate
 * a {@linkplain org.joda.time.DateTime} object using {@linkplain org.joda.time.format.ISODateTimeFormat}.
 * @param resultSet a {@linkplain java.sql.ResultSet}
 * @return a Map with the column names as keys and the values. null if something goes wrong.
 *//*from   w w  w . ja  va2s.  c  o  m*/
public static Map<String, String> resultSetToMap(ResultSet resultSet) {
    Map<String, String> map = new HashMap<String, String>();
    try {
        int columnCount = resultSet.getMetaData().getColumnCount();

        l.trace("Mapping a result set with " + columnCount + " columns to a Map");

        ResultSetMetaData meta = resultSet.getMetaData();
        for (int i = 1; i < columnCount + 1; i++) {
            String colName = meta.getColumnName(i).toLowerCase();
            int colType = meta.getColumnType(i);
            String v = resultSet.getString(i);
            if (colType == Types.DATE) {
                v = new DateTime(resultSet.getDate(i)).toString(dateFTR);
                l.trace("Mapped DATE column " + colName + " with value : " + v);
            } else if (colType == Types.TIMESTAMP) {
                v = new DateTime(resultSet.getTimestamp(i)).toString(dateTimeFTR);
                l.trace("Mapped TIMESTAMP column " + colName + " with value : " + v);
            } else if (colType == Types.TIME) {
                v = new DateTime(resultSet.getTimestamp(i)).toString(timeFTR);
                l.trace("Mapped TIME column " + colName + " with value : " + v);
            } else {
                l.trace("Mapped " + meta.getColumnTypeName(i) + " column " + colName + " with value : " + v);
            }
            map.put(colName, v);
        }
    } catch (SQLException e) {
        l.error("Failed to map ResultSet");
        l.error(e.getMessage());
        return null;
    }

    return map;
}