2015-05-14 34 views
0

我想在Java中使用準備語句執行選擇查詢。 在Where子句中檢查Timestamp類型列上的條件,如下所示。在java sql準備語句中使用時間戳

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 

那麼究竟在這裏哪裏出錯?

在此先感謝。

回答

2

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繼承,它將執行查詢而不準備它。

+0

感謝Akash的解答和解釋。 –