How can I get time with MySql in Java?

I have a column in my table that contains a time data type. I need to print this value. Here is the code I'm using:

Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM student"); System.out.print("\t\t"+rs.getTime("Total Time")); 

Exit 00:00:00, but the actual value in my database is 24:00:00. How can I get the correct value?

+4
source share
2 answers

Call rs.next() before using getTime() to move the cursor forward to the first line:

 Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM student"); if (rs.next()) { System.out.print("\t\t"+rs.getTime("Total Time")); } 

From the documentation:

A ResultSet cursor is initially located up to the first line ; the first call to next makes the first line the current line ; the second call makes the second line the current line, etc.

+1
source

u rs.next () is missing before printing.

To print 24:00: rs.getTime will return a Time object in the format "HH:mm" (00:00 to 23:00) . if you want the time from (01:00-24:00) format the time using the simpledateformat("kk:mm").format() method, as shown below.

 Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM student"); while(rs.next()) { // if resutset not empty System.out.println(new SimpleDateFormat("kk:mm:ss").format(rs.getTime("time").getTime())); // 

}

check out the ResultSet API for more info :)

+1
source

Source: https://habr.com/ru/post/1436982/


All Articles