duxitao
2011-05-31 19:25
浏览 393
已采纳

java多线程、数据库连接池出错,请高手指正,谢谢!

程序运行会报 关闭的语句: next 错误,请高手指正,谢谢!
1、TEST类,启动两个线程。
package main;
public class Test {
public static void main(String[] args){
TestThread t1 =new TestThread();
t1.setName("T1 ");
t1.start();
TestThread t2 =new TestThread();
t2.setName("T2 ");
t2.start();
}
}
2、线程类
package main;

import java.sql.ResultSet;
public class TestThread extends Thread {
int i = 0;
public void run() {
while (i < 20) {
i++;
try {
ResultSet rs = Controller.getInstance().getDB().Query("select SYSTIMESTAMP from dual");
while (rs.next())
System.out.println(rs.getString(1));
System.out.println(this.getName() + i);
Thread.sleep(10);
} catch (Exception e) {
System.out.println(this.getName() + i + " " + e.getMessage());
}
}
}
}
3、控制类
package main;

import datebase.OraPooledSQL;

public class Controller {
static Controller Instance = new Controller();
private OraPooledSQL DB = new OraPooledSQL();
public static Controller getInstance() {
return Instance;
}
public OraPooledSQL getDB() {
return DB;
}
}
4、数据库操作类
package datebase;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.PooledConnection;
import oracle.jdbc.pool.OracleConnectionPoolDataSource;

public class OraPooledSQL {
private PooledConnection dbpool;
public OraPooledSQL() {
try {
String ConnectionURL = "jdbc:oracle:thin:@127.0.0.1:1521:XE";
String UserID = "ivruser";
String PassWord = "ivruser123";
OracleConnectionPoolDataSource ocpds = new OracleConnectionPoolDataSource();
ocpds.setURL(ConnectionURL);
ocpds.setUser(UserID);
ocpds.setPassword(PassWord);
dbpool = ocpds.getPooledConnection();
} catch (Exception ex) {
System.err.println("Error in PooledSQL-construct ");
ex.printStackTrace(System.err);
}
}
protected void finalize() {
if (dbpool != null) {
try {
System.out.println("finalize");
dbpool.close();
} catch (Exception ex) {
}
}
}
public synchronized ResultSet Query(String SQL) throws SQLException {
Statement stmt = null;
ResultSet rs = null;
Connection connection = null;
connection = dbpool.getConnection();
stmt = connection.createStatement();
rs = stmt.executeQuery(SQL);
return rs;
}
}

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • heihei0923 2011-06-01 00:08
    已采纳

    public synchronized ResultSet Query(String SQL) throws SQLException {
    Statement stmt = null;
    ResultSet rs = null;
    Connection connection = null;
    connection = dbpool.getConnection();
    stmt = connection.createStatement();
    rs = stmt.executeQuery(SQL);
    return rs;
    }

    Connection connection 变量为方法私有,调用完成后变为了无效引用;虚拟机会回收资源,connection对象可能这时就在销毁前close()了。
    之后你在rs.next是不是就应该出错了。

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题