jdbc 是线程安全的,但是,推荐一个线程用一个链接
JDBC is thread safe: It is quite OK to pass the various JDBC objects between threads.
For example, you can create the connection in one thread; another thread can use this connection to create a PreparedStatement and a third thread can process the result set. The single major restriction is that you cannot have more than one ResultSet open on a single PreparedStatement at any time. See Does Oracle DB support multiple (parallel) operations per connection?
你不能在一个statment上面存在超过一个打开的resultset(不打开的可以有多个)。
Note that a database commit occurs on a Connection, and so all DML (INSERT, UPDATE and DELETE's) on that connection will commit together. Therefore, if you want to support multiple transactions at the same time, you must have at least one Connection for each concurrent Transaction.
至少一个事物对应一个链接
Users often ask me if our JDBC driver supports multithreaded programming. The answer I always give is a qualifed 'yes'....'but you shouldn't be doing it!'.
mysql的jdbc驱动是线程安全的,但是我们不应该这样用。
Although the JDBC API requires that JDBC drivers support multithreaded access, the JDBC API itself is not designed to be used in a multithreaded way. It is only intended that multithreaded access will not cause the driver to enter an 'unknown' state with regards to communications to the database.
jdbc 要求驱动支持多线程,但他设计不是为了多线程使用。
多线程公用一个connection会引发的问题
1、Committing or rolling back a transaction closes all open ResultSet objects and currently executing Statements, unless you are using held cursors.
If one thread commits, it closes the Statements and ResultSets of all other threads using the same connection.
如果一个线程提交或回滚一个事物会关闭所有打开的 resultset、statement
2、Executing a Statement automatically closes any existing open ResultSet generated by an earlier execution of that Statement.
If threads share Statements, one thread could close another's ResultSet.
执行一个Statement会关闭已经存在的ResultSet
如果多线程共享 Statements,别的线程可能会关闭其他线程的 resultset
数据库连接池的实现及原理
JDBC是一个规范,遵循JDBC接口规范,各个数据库厂家各自实现自己的驱动程序(Driver),如下图所示:
JDBC最常用的资源有三类:
— Connection: 数据库连接。
— Statement: 会话声明。
— ResultSet: 结果集游标。
如果想确定某个数据库连接(Connection)是否超时,则需要确定其(所有的)子Statement是否超时,同样,需要确定所有相关的 ResultSet是否超时;
在关闭Connection前,需要关闭所有相关的Statement和ResultSet。
有些数据库的JDBC Driver并不支持Connection与Statement之间的逻辑连接功能,如SQLServer,我们只能等待她自身的更新版本了。
http://download.nust.na/pub6/mysql/news-and-events/newsletter/2003-04/a0000000154.html
来源:https://www.cnblogs.com/siqi/p/11334436.html