首页 > 解决方案 > PreparedStatement 在传递给 setString 的字符串周围给出两个单引号

问题描述

我试图使用准备好的语句来接收列中的最大值。我收到一个错误,我的函数的输入之一被读取为“表”(双单引号),而不是“表”。我一生都无法理解为什么它会那样放琴弦?是否有一些特殊的方法来格式化 .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

我试图到处寻找答案,但似乎没有人对这个确切的问题有答案。感谢您的所有回复。如果这是某种转发/重复,我深表歉意。

标签: javaprepared-statement

解决方案


推荐阅读