在 java sql 准备语句中使用时间戳

Using Timestamp in java sql prepared statement

我正在尝试使用 Java 中的准备语句执行 select 查询。 在 Where 子句中,我正在检查时间戳类型列的条件,如下所示。

String selectSQL = "select * from db.keycontacts WHERE CREATEDDATETIME>?";
PreparedStatement preparedStatement = connect.prepareStatement(selectSQL);
preparedStatement.setTimestamp(1, convertStrToTimestamp(lastSyncTimeStamp));
resultSet = preparedStatement.executeQuery(selectSQL );

//将timestampString转换为java.sql.Timestamp

的函数
private java.sql.Timestamp convertStrToTimestamp(String dateTimeStr){

      java.sql.Timestamp timeStampDate = null;
      try {
            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//2015-05-11 18:26:55
            java.util.Date dateObj = (java.util.Date)formatter.parse(dateTimeStr);
            timeStampDate = new Timestamp(dateObj.getTime());
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

      return timeStampDate;
  }

执行查询时,出现如下异常。

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1

所以我到底哪里出了问题?

提前致谢。

中删除参数
resultSet = preparedStatement.executeQuery(selectSQL );

并更改为

resultSet = preparedStatement.executeQuery( );

您在 preparedStatement.executeQuery(selectSQL ); 中传递的查询优先于您在 connect.prepareStatement(selectSQL); 中传递的查询,后者是您在其中设置任何参数的简单字符串 ("select * from db.keycontacts WHERE CREATEDDATETIME>?"),因此有?

的语法错误

你也可以说语句是在 PreparedStatement preparedStatement = connect.prepareStatement(selectSQL); 准备的,因为 executeQuery() 是从 Statement 继承的,它会在不准备的情况下执行查询。

    Class.forName("com.mysql.cj.jdbc.Driver");
    Connection con = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/test","root","rootpasswd");
    PreparedStatement ps = con.prepareStatement("select p.PARKING_NUMBER, p.TYPE, p.AVAILABLE, "
            + "t.PARKING_NUMBER, t.VEHICLE_REG_NUMBER, t.PRICE, t.IN_TIME, t.OUT_TIME "
            + "from parking p inner join ticket t on p.PARKING_NUMBER = t.PARKING_NUMBER "
            + "where t.In_TIME = ?");
    Timestamp ts = new Timestamp(BigDecimal.valueOf(expectedInTime.getTime()/1000d).setScale(0, RoundingMode.HALF_UP).longValue()*1000);
    //To Round Half Up from millisecond (d for double) to second (long so no d) because MySQL do this.
    ps.setTimestamp(1, ts);
    ResultSet rs = ps.executeQuery();