多线程JDBC [英] Multithreaded JDBC

查看:139
本文介绍了多线程JDBC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从结构上讲,处理具有多个线程的JDBC的最佳方法是什么?我有许多线程同时访问数据库.通过一个连接和一条语句,我得到以下错误消息:

Architecturally what is the best way to handle JDBC with multiple threads? I have many threads concurrently accessing the database. With a single connection and statement I get the following error message:

org.postgresql.util.PSQLException:该结果集已关闭.

org.postgresql.util.PSQLException: This ResultSet is closed.

我应该使用多个连接,多个语句还是有更好的方法?我的初步想法是每个线程使用一个语句,这样可以保证每个语句只有一个结果集.

Should I use multiple connections, multiple statements or is there a better method? My preliminary thought was to use one statement per thread which would guarantee a single result set per statement.

推荐答案

每个任务应使用一个连接.如果使用连接池,则不能使用其他连接准备的准备好的语句.将连接返回到池后,由连接创建的所有对象(ResultSet,PreparedStatements)均无效.

You should use one connection per task. If you use connection pooling you can't use prepared statements prepared by some other connection. All objects created by connection (ResultSet, PreparedStatements) are invalid for use after connection returned to pool.

所以,就像

public void getSomeData() {
  Connection conn = datasource.getConnection();
  PreparedStatement st;
  try {
    st = conn.prepareStatement(...);
    st.execute();
  } finally {
    close(st);
    close(conn);
  }
}

因此,在这种情况下,您的所有DAO对象都不采用Connection,而是采用DataSource对象(java.sql.DataSource),它实际上是可池化的连接工厂.并且,在每种方法中,您首先都需要建立连接,进行所有工作并关闭连接.您应该尽快将连接返回到池中.返回连接后,它可能不会被物理关闭,而是被重新初始化(所有活动事务已关闭,所有会话变量已销毁,等等)

So in this case all your DAO objects take not Connection, but DataSource object (java.sql.DataSource) which is poolable connection factory indeed. And in each method you first of all get connection, do all your work and close connection. You should return connection to pool as fast as possible. After connection returned it may not be physically closed, but reinitialized (all active transactions closed, all session variables destroyed etc.)

这篇关于多线程JDBC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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