java - 使用单个 JDBC Statement 对象执行多个查询

标签 java mysql sql jdbc

在 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/

相关文章:

java - 无法运行Java程序

java - @OneToMany List<> vs Set<> 区别

sql - 如何将 SQL 中的循环转换为基于 Set 的逻辑

mysql - SQL 中的 And Or 条件,但未正确嵌套它们

java - 以编程方式安装应用程序

java - 使用 GTKLookAndFeel 的具有 JLabel 样式的 JTextField

mysql - MySQL中是否有一个函数可以删除与另一个多边形相交的多边形

php - 将返回多个平均值的 SQL 查询

php - 无法增加/减少 php 中的重载对象或字符串偏移量

sql - Cosmos 批量读取项查询