gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:37:34 24 4
gpt4 key购买 nike

我正在尝试使用 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 继承的。它将执行查询而不准备它。

关于java - 在java sql准备语句中使用时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30230513/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com