Get TIME value from ResultSet in Java

Description

The following code shows how to get TIME value from ResultSet.

Example


  /*w  ww.j a v a  2  s . c o  m*/

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

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

    st.executeUpdate("create table survey (id int,myDate TIME );");
    String INSERT_RECORD = "insert into survey(id, myDate) values(?, ?)";
    
    PreparedStatement pstmt = conn.prepareStatement(INSERT_RECORD);
    pstmt.setString(1, "1");
    java.sql.Time  sqlDate = new java.sql.Time(new java.util.Date().getTime());
    pstmt.setTime(2, sqlDate);
    
    pstmt.executeUpdate();
    
    ResultSet rs = st.executeQuery("SELECT * FROM survey");

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

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

  private static Connection getConnection() throws Exception {
    Class.forName("org.hsqldb.jdbcDriver");
    String url = "jdbc:hsqldb:mem:data/tutorial";

    return DriverManager.getConnection(url, "sa", "");
  }
}  

The code above generates the following result.





















Home »
  Java Tutorial »
    JDBC »




Batch
Binary Data
Database
Date Time
Insert
ResultSet
SQL
Statement
Stored Function
Table