【问题标题】:Using Timestamp in java sql prepared statement在java sql准备语句中使用时间戳
【发布时间】:2015-07-25 16:00:24
【问题描述】:

我正在尝试使用 Java 中的准备好的语句执行选择查询。 在 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

那么我到底哪里出错了?

提前致谢。

【问题讨论】:

    标签: java mysql sql-server prepared-statement sql-timestamp


    【解决方案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 继承的,它将在不准备的情况下执行查询。

    【讨论】:

    • 感谢 Akash 的解决方案和解释。
    猜你喜欢
    • 2013-08-12
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-28
    相关资源
    最近更新 更多