Java + JDBC:预处理语句失败

时间:2018-12-07 22:39:08

标签: java mysql sql jdbc

我正在尝试准备一条语句,而驱动程序正在按假定的方式工作,但是唯一的问题是我的查询不再有效。

我正在尝试编写此查询:

SELECT ip_address
FROM log_activity
WHERE created_at
  BETWEEN "2017-01-01 00:00:00"
  AND DATE_ADD("2017-01-01 00:00:00", INTERVAL 1 HOUR)
GROUP BY ip_address
HAVING COUNT(*) > 200;

但是在插入准备好的语句的参数之后,它显示为:

SELECT ip_address
FROM log_activity
WHERE created_at
  BETWEEN '\'2017-01-01 00:00:00\''
  AND DATE_ADD('\'2017-01-01 00:00:00\'', INTERVAL 1 'hour')
GROUP BY ip_address
HAVING COUNT(*) > 200;

哪个不再是有效的SQL。那么,如何从参数中删除这些引号?或者有什么好的方法来解决此问题?

...

String startDateArg = "'" + args[0].split("=", 2)[1].replace(".", " ") + "'";
String durationArg = args[1].split("=", 2)[1];
int thresholdArg = Integer.parseInt(args[2].split("=", 2)[1]);

String duration = durationArg.equals("hourly") ? "hour" : durationArg.equals("daily") ? "day" : null;

String getUsersOverAPILimitQuery = "" +
    "select ip_address " +
    "from log_activity " +
    "where created_at " +
    "  between ?" +
    "  and date_add(?, interval 1 ?) " +
    "group by ip_address " +
    "having count(*) > ?;";
PreparedStatement preparedStatement = con.prepareStatement(getUsersOverAPILimitQuery);
preparedStatement.setString(1, startDateArg);
preparedStatement.setString(2, startDateArg);
preparedStatement.setString(3, duration);
preparedStatement.setInt(4, thresholdArg);

System.out.println(preparedStatement);

ResultSet getUsersOverAPILimit = preparedStatement.executeQuery();

while (getUsersOverAPILimit.next()) {
    String ip_address = getUsersOverAPILimit.getString("ip_address");
    System.out.println(ip_address);
}

...

1 个答案:

答案 0 :(得分:2)

代替此:

String startDateArg = "'" + args[0].split("=", 2)[1].replace(".", " ") + "'";

执行以下操作:

String startDateArg = args[0].split("=", 2)[1].replace(".", " ");

无需添加单引号,preparedstatement即可为您完成。