在java應(yīng)用中,我們會(huì)經(jīng)常用oracle jdbc.在開發(fā)中我們有時(shí)候會(huì)遇到(ORA-01000: maximum open cursors
exceeded)的錯(cuò)誤。在ITPUB上juant曾發(fā)過一篇帖子:http://www.itpub.net/showthread.php?
s=&threadid=122832&perpage=15&pagenumber=1
[TIP]關(guān)于Java開發(fā)中使用Oracle數(shù)據(jù)庫的一點(diǎn)注意事項(xiàng)(原創(chuàng))
很多朋友在Java開發(fā)中,使用Oracle數(shù)據(jù)庫的時(shí)候,經(jīng)常會(huì)碰到有ORA-01000: maximum open cursors exceeded.的
錯(cuò)誤。
實(shí)際上,這個(gè)錯(cuò)誤的原因,主要還是代碼問題引起的。
ora-01000: maximum open cursors exceeded.
表示已經(jīng)達(dá)到一個(gè)進(jìn)程打開的最大游標(biāo)數(shù)。
這樣的錯(cuò)誤很容易出現(xiàn)在Java代碼中的主要原因是:Java代碼在執(zhí)行conn.createStatement()和
conn.prepareStatement()的時(shí)候,實(shí)際上都是相當(dāng)與在數(shù)據(jù)庫中打開了一個(gè)cursor。尤其是,如果你的
createStatement和prepareStatement是在一個(gè)循環(huán)里面的話,就會(huì)非常容易出現(xiàn)這個(gè)問題。因?yàn)橛螛?biāo)一直在不停的打
開,而且沒有關(guān)閉。
一般來說,我們?cè)趯慗ava代碼的時(shí)候,createStatement和prepareStatement都應(yīng)該要放在循環(huán)外面,而且使用了這些
Statment后,及時(shí)關(guān)閉。最好是在執(zhí)行了一次executeQuery、executeUpdate等之后,如果不需要使用結(jié)果集
(ResultSet)的數(shù)據(jù),就馬上將Statment關(guān)閉。
對(duì)于出現(xiàn)ORA-01000錯(cuò)誤這種情況,單純的加大open_cursors并不是好辦法,那只是治標(biāo)不治本。實(shí)際上,代碼中的隱
患并沒有解除。
而且,絕大部分情況下,open_cursors只需要設(shè)置一個(gè)比較小的值,就足夠使用了,除非有非常特別的要求。
對(duì)這個(gè)問題專門研究了一下,并寫了測(cè)試程序,首先說一些測(cè)試環(huán)境,我們的數(shù)據(jù)庫最大可打開的cursor設(shè)置為600,操
作的數(shù)據(jù)庫表的記錄數(shù)為30條記錄。為了模擬同時(shí)打開600cursor,也就是說有600個(gè)statement在運(yùn)行,必須用到j(luò)ava
的多線程。下面是測(cè)試程序:
public class StatementTest extends Thread{
private Connection conn;
public StatementTest(Connection conn) {
this.conn = conn;
start();
}
public void run(){
try {
String strSQL = "SELECT * FROM TestTable"
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(strSQL);
int i = 0;
while(rs.next()){
System.out.println("----"+i+"------");
i = i+1;
}
rs.close();
stmt.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static void main(String args[]){
try{
Connection conn = DBConnection.getConnection();
for(int i = 0;i < 800;i++){
new StatementTest(conn);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
本Blog純屬個(gè)人學(xué)習(xí)、工作需要,記錄相關(guān)資料。請(qǐng)不要發(fā)表任何有人身攻擊的言論,謝謝! www.zhipsoft.cn
posted on 2007-07-31 15:12
ZhipSoft 閱讀(1345)
評(píng)論(0) 編輯 收藏 所屬分類:
DataBase