天天看點

java 連接配接池 線程安全_JDBC 線程安全 資料庫連接配接池

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 isa 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 要求驅動支援多線程,但他設計不是為了多線程使用。

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),如下圖所示:

java 連接配接池 線程安全_JDBC 線程安全 資料庫連接配接池

JDBC最常用的資源有三類:

— Connection: 資料庫連接配接。

— Statement: 會話聲明。

— ResultSet: 結果集遊标。

java 連接配接池 線程安全_JDBC 線程安全 資料庫連接配接池

如果想确定某個資料庫連接配接(Connection)是否逾時,則需要确定其(所有的)子Statement是否逾時,同樣,需要确定所有相關的 ResultSet是否逾時;

在關閉Connection前,需要關閉所有相關的Statement和ResultSet。

有些資料庫的JDBC Driver并不支援Connection與Statement之間的邏輯連接配接功能,如SQLServer,我們隻能等待她自身的更新版本了。