gpt4 book ai didi

java - 如何修复PreparedStatement.setString中的 "Declaration, final or effectively final variable expected"

转载 作者:行者123 更新时间:2023-12-01 19:39:02 25 4
gpt4 key购买 nike

问题是我试图在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 "";
}
/* 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)
);

最佳答案

您无法在 try-with-resources 中设置 stmt 参数(因为绑定(bind)参数是 void 而不是 可关闭)。相反,您可以在绑定(bind)参数后嵌套第二个 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 "";
}

关于java - 如何修复PreparedStatement.setString中的 "Declaration, final or effectively final variable expected",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56050481/

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