2015-09-08 115 views
1

我有一个表timestamptest,其中一列timestamp的类型为timestamp without time zoneJava ResultSet.getTimestamp()将毫秒附加到输出

我插入一个值,这个表:
insert into timestamptest values('2015-09-08 13:11:11')

时间戳不包含任何的毫秒数。
在pgAdmin中选择该数据时,显示与上述相同。

但是,当我使用jdbc连接获取此数据时,显示的值为毫秒。

Class.forName("org.postgresql.Driver"); 
    Connection lConnection = null; 
    lConnection = DriverManager.getConnection(
     "jdbc:postgresql://localhost:5432/postgres","postgres", "[email protected]"); 
    String lQuery = "select * from timestamptest"; 
    Statement lStatement = lConnection.createStatement(); 
    ResultSet lResultSet = lStatement.executeQuery(lQuery); 
    while(lResultSet.next()) { 
     System.out.println(lResultSet.getTimestamp(1)); 
    } 

输出:2015-09-08 13:11:11.0

所需的输出是2015-09-08 13:11:11

它可以通过使用的SimpleDateFormat来实现:
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(lResultSet.getTimestamp(1).getTime())

它可以是可能的,而不使用的SimpleDateFormat?有没有其他的方式可以让结果集以我想要的格式给我?

我需要的是该语句 lResultSet.getTimestamp(1)
直接给我的输出2015-09-08 13:11:11

+0

“*是否可能不使用SimpleDateFormat *?” - 没有。这是如何定义'java.sql.Timestamp'上的'toString()'方法:http://docs.oracle.com/javase/7/docs/api/java/sql/Timestamp.html#toString%28 %29 –

回答

0

它是不可能的。由于ResultSet.getTimestamp(1)返回的类延伸java.sql.TimeStamp。基于数据库驱动程序返回课程。而且我们也不能改变toString的实现。

0

是的,你可以 - 但你不会喜欢它。

class MyTimestamp extends Timestamp { 

    public MyTimestamp(long time) { 
     super(time); 
    } 

    public MyTimestamp(Timestamp ts) { 
     this(ts.getTime()); 
    } 

    @Override 
    public String toString() { 
     String s = super.toString(); 
     return s.substring(0, s.lastIndexOf(".")); 
    } 
} 

public void test() { 
    System.out.println("Hello"); 
    Timestamp t = new Timestamp(System.currentTimeMillis()); 
    System.out.println(t); 
    System.out.println(new MyTimestamp(t)); 

}