使用单个JDBC语句对象执行多个查询 [英] Execute multiple queries using a single JDBC Statement object

查看:635
本文介绍了使用单个JDBC语句对象执行多个查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将其标记为重复之前,请先阅读.我从Google和SO搜索了很多内容,但是我找不到我想要的确切答案.

Please read before marking this as duplicate. I have searched a lot from google and SO, but I couldn't the precise answer I am looking for.

我的问题:在JDBC中,我可以使用单个Statement对象多次调用executeQuery("")吗?安全吗?或者应该在每次查询后关闭语句对象,并创建新对象以执行另一个查询.

My Question: In JDBC, Can I use single Statement object to call executeQuery("") multiple times? Is it safe? OR should I close the statement object after each query, and create new object for executing another query.

E.G:

Connection con;
Statement s;
ResultSet rs;
ResultSet rs2;
try
{
    con = getConnection();
    s = con.prepareStatement();

    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对象,则为错误的样式.至于关闭它,就像在此代码段中一样,将其最终关闭是合适的.

Yes you can re-use a Statement(specifically a PreparedStatement) and should do so in general with JDBC. It would be inefficient & bad style if you didn't re-use your statement and immediately created another identical Statement object. As far as closing it, it would be appropriate to close it in a finally block, just as you are in this snippet.

有关您要查询的内容的示例,请查看以下链接: jOOq文档

For an example of what you're asking check out this link: jOOq Docs

这篇关于使用单个JDBC语句对象执行多个查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆