如何修复PreparedStatement.setString中的“预期声明、最终或有效最终变量”

Jat*_*ard 1 java sql intellij-idea

问题是我试图在PreparedStatement 中设置通配符,但setString 语句给了我上面的错误。

我尝试将其更改为具有多种不同类型(如 Types.VARCHAR)的 setObeject 语句。我尝试在不同的地方声明PreparedStatement,并且尝试在方法和类中声明“名称”。

public String getTemplateText(String name) {
    try (
            Connection conn = getConnection();
            PreparedStatement stmt = conn.prepareStatement("SELECT templateText FROM TEMPLATE WHERE " +
                    "templateTag = ?");
            stmt.setString(1 , name); // this is the line that has the problem!
            ResultSet rs = stmt.executeQuery()
    ) {
        System.out.println("Set Text...");
        String tempText = rs.getString("templateText");
        return tempText;
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return "";
}
Run Code Online (Sandbox Code Playgroud)
/* this is the SQL code for the table that I am trying to query */
CREATE TABLE TEMPLATE
(
    templateID      INTEGER PRIMARY KEY IDENTITY(1,1)
  , templateText    TEXT
  , templateTag     CHAR(25)
);
Run Code Online (Sandbox Code Playgroud)

Ell*_*sch 7

您无法stmt在您的中设置参数try-with-resources(因为绑定参数是void且不可closeable)。相反,您可以try-with-resources在绑定参数后嵌套一秒钟。喜欢,

public String getTemplateText(String name) {
    try (Connection conn = getConnection();
            PreparedStatement stmt = conn
                    .prepareStatement("SELECT templateText FROM TEMPLATE WHERE " + 
                    "templateTag = ?")) {
        stmt.setString(1, name);
        try (ResultSet rs = stmt.executeQuery()) {
            System.out.println("Set Text...");
            String tempText = rs.getString("templateText");
            return tempText;
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return "";
}
Run Code Online (Sandbox Code Playgroud)