gpt4 book ai didi

java - 如何将表名传递给 SELECT COUNT 查询中的准备语句?

转载 作者:行者123 更新时间:2023-11-30 06:43:06 24 4
gpt4 key购买 nike

所以我有以下方法,效果很好:

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)

我做错了什么?

最佳答案

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

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

请注意,此查询中没有占位符,因此与普通的旧 Statement 相比,使用 PreparedStatement 是否真的有任何优势是值得怀疑的。

关于java - 如何将表名传递给 SELECT COUNT 查询中的准备语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44083883/

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