跨线程共享连接的 JDBC 自动提交

发布于 2024-10-19 03:19:00 字数 191 浏览 5 评论 0原文

我有一个 Servlet,在其中获取一个 Connection 对象,然后将该对象传递给两个工作线程以进行各种活动。我现在需要在一个线程上添加一项事务。

如果我开始这样的交易: 连接.setAutoCommit(假);

这会影响两个线程吗?我想会的。

我是否必须为每个线程建立单独的连接?

谢谢

I have a servlet where I get a Connection object which is then handed to two worker threads for various activities. I now need to add a transaction on one thread.

If I start a transaction like this:
connection.setAutoCommit(false);

would that impact both threads? I think it would.

Do I have to get a separate connection of each thread?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

Spring初心 2024-10-26 03:19:00

我认为你所做的事情是非常糟糕的做法。您不能在线程之间共享 JDBC 连接。

如果您在应用程序服务器(如 TOMCAT/JBoss/WebSphere/WebLogic)下运行,请使用适当的数据源来根据需要获取连接。

查看应用程序服务器文档以获取有关如何执行此操作的信息。

您的 servlet 中将有类似的内容:

public void doGet(HttpServletRequest req, HttpServletResponse resp)
{
    Connection c = null;
    try {
        c = ...; /* preferred way of getting a connection in your AppServer
        // do what you need with your JDBC connection
    } catch (Exception e) {
        // handle errors
    } finally {
        c.close(); /* you will need another TRY/CATCH here */
    }
}

同样,您的工作线程将有类似的内容:

public void run()
{
    Connection c = null;
    try {
        c = ...; /* preferred way of getting a connection in your AppServer
        // do what you need with your JDBC connection
    } catch (Exception e) {
        // handle errors
    } finally {
        c.close(); /* you will need another TRY/CATCH here */
    }
}

最终,您可以将 自动提交 设置为单独连接对象上所需的任何内容。

I think what you are doing is very bad practice. You can't share a JDBC connection among threads.

If you are running under an application server (like TOMCAT/JBoss/WebSphere/WebLogic) use a proper DataSource to get your connections as you need them.

Look at your Application Server documentation to get information on how to do that.

You will have something like this in your servlet:

public void doGet(HttpServletRequest req, HttpServletResponse resp)
{
    Connection c = null;
    try {
        c = ...; /* preferred way of getting a connection in your AppServer
        // do what you need with your JDBC connection
    } catch (Exception e) {
        // handle errors
    } finally {
        c.close(); /* you will need another TRY/CATCH here */
    }
}

Similarly, your worker threads will have something like:

public void run()
{
    Connection c = null;
    try {
        c = ...; /* preferred way of getting a connection in your AppServer
        // do what you need with your JDBC connection
    } catch (Exception e) {
        // handle errors
    } finally {
        c.close(); /* you will need another TRY/CATCH here */
    }
}

Eventually, you could set auto commit to whatever you need on separate connection objects.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文