簡體   English   中英

在java sql准備語句中使用時間戳

[英]Using Timestamp in java sql prepared statement

我正在嘗試使用 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

那么我到底哪里出錯了?

提前致謝。

刪除參數

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM