用于TimeStamp比较的PrepareStatement的字符串值

时间:2018-02-11 19:15:55

标签: java sql-server jdbc timestamp

使用TimeStamp的WHERE子句从表中选择数据。 我想设置一个从TextField重新获得的String值来显示过滤表。

不工作:

public ResultSet queryAlarms() throws SQLException
String sql = "SELECT * FROM BDCS.dbo.Alarms WHERE AlarmTime > ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, " '2017-12-29 14:45' ");
return ps.executeQuery();
}

WORKING:

public ResultSet queryAlarms() throws SQLException {
String sql = "SELECT * FROM BDCS.dbo.Alarms WHERE AlarmTime > '2017-12-29 14:45'";
PreparedStatement ps = connection.prepareStatement(sql);
return ps.executeQuery();
}

有人知道如何正确发送值吗?或者更好的方法是什么?

1 个答案:

答案 0 :(得分:0)

试试这个..!

preparedStatement.setTimestamp(1,getCurrentTimeStamp());

您也可以使用text-field字符串生成时间戳。

private static java.sql.Timestamp getCurrentTimeStamp() {

    java.util.Date today = new java.util.Date();
    return new java.sql.Timestamp(today.getTime());

}


private static Timestamp getTimeStamp(String ts){

 //Change the format as per your requirement
  DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
  Date date = dateFormat.parse(ts));
  long time = date.getTime();
  new Timestamp(time);

}