kdot
kdot

Reputation: 129

How can I get the time from MySql in Java?

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

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

The output is 00:00:00, but the actual value in my database is 24:00:00. How can I get the right value?

Upvotes: 4

Views: 811

Answers (2)

PermGenError
PermGenError

Reputation: 46408

u are missing rs.next() before you print.

To print 24:00: rs.getTime will return Time object with format "HH:mm" (00:00 to 23:00). if you want the time from (01:00-24:00) format the time using simpledateformat("kk:mm").format() method like 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 the ResultSet API for more information :)

Upvotes: 1

João Silva
João Silva

Reputation: 91299

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

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 positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

Upvotes: 1

Related Questions