JDBC PreparedStatement似乎忽略了占位符

时间:2017-09-22 17:13:48

标签: java sql sqlite jdbc

考虑到PreparedStatement的以下代码,我使用占位符(?)填充String

String sql = "SELECT SUM(Premium), SUM(AgentComm)\n" +
                "FROM \"?_KLCommissions\" \n" +
                "WHERE AgentCode = \"?\";";

    PreparedStatement preparedStatement = conn.prepareStatement(sql);
    preparedStatement.setString(1, year);
    preparedStatement.setString(2, agent.getAgentNumber());

    ResultSet resultSet = preparedStatement.executeQuery();

但是,在执行查询时,出现SQL错误:no such table: ?_KLCommissions

为什么处理查询时?占位符没有被替换?

1 个答案:

答案 0 :(得分:2)

你有双引号,这意味着它不是占位符 - 它只是价值的一部分。

除此之外,大多数 SQL数据库不允许您使用表名和列名等参数 - 只能参数化。所以你可能需要直接构建表名部分,然后使用

WHERE AgentCode = ?

代理代码 - 因此您只需要设置一个参数。如下所示:

String tableName = year + "_KLCommissions";
// TODO: Put validation here unless you already have *complete confidence*
// that the value of "year" can't be messed around with.
String sql = "SELECT SUM(Premium), SUM(AgentComm) " +
             "FROM " + tableName + " " +
             "WHERE AgentCode = ?";

PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, agent.getAgentNumber());
ResultSet resultSet = preparedStatement.executeQuery();

注意那里的TODO - 你真的不希望用户能够为year提供任意值,因为他们可以在查询中放置任意SQL。