How to pass table name to a Prepared Statement in a SELECT COUNT query? [duplicate]

我怕爱的太早我们不能终老 提交于 2019-12-24 07:27:39

问题


So I have this following method which works just fine:

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();
}

but when I try:

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();
}

I get:

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)

What am I doing wrong?


回答1:


You can only bind values in a PreparedStatement, not syntactic elements or object names (in this case, the table name). You'll have to resort to string manipulation:

final String query = String.format("SELECT COUNT(*) FROM %s", tablename);
final PreparedStatement preparedStatement = connection.prepareStatement(query);
final ResultSet resultSet = preparedStatement.executeQuery();

Note that there are no placeholders in this query, so it's questionable whether there's really any advantage in using a PreparedStatement as opposed to a plain old Statement.



来源:https://stackoverflow.com/questions/44083883/how-to-pass-table-name-to-a-prepared-statement-in-a-select-count-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!