JDBC 線程安全 數據庫鏈接池

 

jdbc 是線程安全的,可是,推薦一個線程用一個連接

JDBC is thread safe: It is quite OK to pass the various JDBC objects between threads.html

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?java

  你不能在一個statment上面存在超過一個打開的resultset(不打開的能夠有多個)。mysql

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.sql

  至少一個事物對應一個連接數據庫

 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.oracle

  jdbc 要求驅動支持多線程,但他設計不是爲了多線程使用。  less

 

多線程公用一個connection會引起的問題

  一、Committing or rolling back a transaction closes all open ResultSet objects and currently executing Statements, unless you are using held cursors.ide

If one thread commits, it closes the Statements and ResultSets of all other threads using the same connection.

  若是一個線程提交或回滾一個事物會關閉全部打開的 resultset、statement

  

  二、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

相關文章
相關標籤/搜索