在 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);
}
最佳答案
是的,您可以重复使用 Statement
(特别是 PreparedStatement
)并且通常应该使用 JDBC 这样做。如果您不重新使用您的语句并立即创建另一个相同的 Statement
对象,那将是低效和糟糕的风格。至于关闭它,最好在 finally block 中关闭它,就像您在此代码段中一样。
如需了解您所询问的内容,请查看此链接:jOOq Docs
关于java - 使用单个 JDBC Statement 对象执行多个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21327012/