在 JDBC 中,我可以使用单个 Statement
对象来多次调用 executeQuery("")
吗?安全吗?或者我应该在每次查询后关闭语句对象,并创建新对象以执行另一个查询。
例如:
Connection con;
Statement s;
ResultSet rs;
ResultSet rs2;
try
{
con = getConnection();
// Initially I was creating the Statement object in an
// incorrect way. It was just intended to be a pseudocode.
// But too many answerers misinterpretted it wrongly. Sorry
// for that. I corrected the question now. Following is the
// wrong way, commented out now.
// s = con.prepareStatement();
// Following is the way which is correct and fits for my question.
s = con.createStatement();
try
{
rs = s.executeQuery(".......................");
// process the result set rs
}
finally
{
close(rs);
}
// I know what to do to rs here
// But I am asking, should I close the Statement s here? Or can I use it again for the next query?
try
{
rs2 = s.executeQuery(".......................");
// process the result set rs2
}
finally
{
close(rs2);
}
}
finally
{
close(s);
close(con);
}
原文由 Syed Aqeel Ashiq 发布,翻译遵循 CC BY-SA 4.0 许可协议
我不确定你为什么要问。 The API design and documentation show it is perfectly fine (and even intended) to reuse a
Statement
object for multipleexecute
,executeUpdate
andexecuteQuery
电话。如果不允许,则将在 Java 文档中明确记录(并且 API 可能会有所不同)。此外
Statement
的 apidoc 说:这表明您可以多次使用它。
TL;DR:是的,您可以在单个
Statement
对象上多次调用execute
,只要您意识到之前打开的任何ResultSet
将被关闭。您的示例错误地使用
PreparedStatement
,并且您不能(或:不应)调用任何 接受String
的execute...
PreparedStatement
:但是要回答
PreparedStatement
以及:PreparedStatement
的全部目的是预编译带有参数占位符的语句并将其重用于具有不同参数值的多次执行。