我尝试使用prepared语句在列中接收最大值。我收到一个错误,我函数的输入之一被读为“表”(双单引号),而不是“表”。我一辈子都无法理解为什么会放这样的琴弦?有什么特殊的方法可以将输入格式设置为.setString()?
我的功能如下:
public static int getMax(String table, String column){
//You'll have to replace this with your own connection if you want to try and run it
try(Connection connection = ConnectionPool.getConnection();
//This is the statement.
PreparedStatement getMax = connection.prepareStatement("select max(?) from ?")){
getMax.setString(1, column);
getMax.setString(2, table);
ResultSet max = getMax.executeQuery();
if (max.next()){
int m = max.getInt(1);
try{
max.close();
return m;
}
catch (SQLException e){
System.out.println("SQL Error: Could not close max getter. " + e.getMessage());
}
}
else{
try{
max.close();
}
catch (SQLException e){
System.out.println("SQL Error: Could not close max getter. " + e.getMessage());
}
return -1;
}
}
catch (SQLException e){
System.out.println("SQL Error: " + e.getMessage());
return -1;
} catch (Exception e) {
System.out.println("Other error: " + e.getMessage());
}
return -1;
}
大多数是错误捕获,但是我希望代码仍然可读。
我收到此错误:
SQL Error: 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 ''resources'' at line 1
我一直在尝试寻找答案,但是似乎没有人对这个确切的问题有答案。感谢您的所有回复。抱歉,这是某种形式的转发/重复。