[英]How can I convert sql time to java time for an object?
When i run this code it says this: 当我运行此代码时,它说:
Error:(43, 31) java: incompatible types: java.sql.Time cannot be converted to java.time.LocalTime 错误:(43,31)Java:不兼容的类型:java.sql.Time无法转换为java.time.LocalTime
public TrackTime read(int id){
rs = jdbc.queryForRowSet("SELECT * FROM tracktime where id ='" + id + "'");
while (rs.next()){
return new TrackTime (rs.getInt("id"),
rs.getDate("date"),
rs.getTime("startTime"),
rs.getTime("endTime"),
rs.getString("licenseType"),
rs.getInt("trackNumber"));
}
return new TrackTime();
}
what can be the cause of this error? 该错误的原因是什么?
As others have said already, this must be because you TrackTime
constructor expects arguments of type LocalTime
while rs.getTime
returns java.sql.Time
. 正如其他人已经说过,这一定是因为你TrackTime
构造函数需要参数类型的LocalTime
而rs.getTime
返回java.sql.Time
。
Assuming JDBC 4.2 (or higher; you probably have that), use getObject
to retrieve java.time classes like LocalTime
and also LocalDate
from your result set: 假设JDBC 4.2(或更高;你可能有),使用getObject
检索java.time类,如LocalTime
,也LocalDate
从你的结果集:
return new TrackTime (rs.getInt("id"),
rs.getObject("date", LocalDate.class),
rs.getObject("startTime", LocalTime.class),
rs.getObject("endTime", LocalTime.class),
rs.getString("licenseType"),
rs.getInt("trackNumber"));
I have taken the freedom of also changing the retrieval of the date, which will probably give you a new compile-time error. 我也自由更改了日期的检索,这可能会给您带来新的编译时错误。 But now that you are already using java.time, it may be better to change the TrackTime
constructor to accept a LocalDate
? 但是,既然您已经在使用java.time,则最好更改TrackTime
构造函数以接受LocalDate
吗?
If your JDBC driver is not yet JDBC 4.2 compliant, consider upgrading. 如果您的JDBC驱动程序尚未兼容JDBC 4.2,请考虑升级。
Your constructor for TrackTime
class must be expecting object of class LocalTime
where as rs.getTime("startTime")
returns java.sql.Time
instead of LocalTime
and as both are not same hence you get the error. 您的构造TrackTime
类一定是在类的对象LocalTime
在那里为rs.getTime("startTime")
返回java.sql.Time
而不是LocalTime
和都是不相同的,因此你的错误。
You can use toLocalTime()
method on Time
object which returns LocalTime
object and this way correct object type would get passed to your constructor and should get away from the error. 您可以在Time
对象上使用toLocalTime()
方法,该方法返回LocalTime
对象,这样正确的对象类型将传递给您的构造函数,并且应该避免该错误。
So in your code you need to do this, 因此,在您的代码中,您需要执行此操作,
while (rs.next()){
return new TrackTime (rs.getInt("id"),
rs.getDate("date"),
rs.getTime("startTime").toLocalTime(),
rs.getTime("endTime").toLocalTime(),
rs.getString("licenseType"),
rs.getInt("trackNumber"));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.