如何在SELECT COUNT查询中将表名传递给Prepared Statement?

时间:2017-05-20 08:56:24

标签: java jdbc prepared-statement

所以我有以下方法可以正常工作:

static void getCount(final String url, final String username, final String password) throws SQLException {
    final Connection connection = DriverManager.getConnection(url, username, password);

    final String query = "SELECT COUNT(*) FROM app_user";
    final PreparedStatement preparedStatement = connection.prepareStatement(query);
    final ResultSet resultSet = preparedStatement.executeQuery();

    resultSet.next();
    System.out.println(resultSet.getInt(1));

    resultSet.close();
    preparedStatement.close();
    connection.close();
}

但是当我尝试时:

static void foobar(final String url, final String username, final String password, final String tablename) throws SQLException {
    final Connection connection = DriverManager.getConnection(url, username, password);

    final String query = "SELECT COUNT(*) FROM ? ";
    final PreparedStatement preparedStatement = connection.prepareStatement(query);
    preparedStatement.setString(1, tablename);
    final ResultSet resultSet = preparedStatement.executeQuery();

    resultSet.next();
    System.out.println(resultSet.getInt(1));

    resultSet.close();
    preparedStatement.close();
    connection.close();
}

我明白了:

Exception in thread "main" 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 ''app_user'' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您只能绑定n^3中的值,而不能绑定语法元素或对象名称(在本例中为表名)。你不得不诉诸字符串操作:

PreparedStatement

请注意,此查询中没有占位符,因此使用final String query = String.format("SELECT COUNT(*) FROM %s", tablename); final PreparedStatement preparedStatement = connection.prepareStatement(query); final ResultSet resultSet = preparedStatement.executeQuery(); 而不是普通的PreparedStatement确实是否有任何优势是值得怀疑的。< / p>