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 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,我們只能等待她自身的更新版本了。

 

參考
https://stackoverflow.com/questions/12192592/java-sql-sqlexception-ora-01000-maximum-open-cursors-exceeded

http://download.nust.na/pub6/mysql/news-and-events/newsletter/2003-04/a0000000154.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM