数据源的JAVABEAN如下:
package mybean;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
public class DBConnSource {
    private Connection conn;
    private Statement stmt;
    private PreparedStatement pstmt;
    public DBConnSource(String dsName){
     try{
     Context initCtx = new InitialContext();
     Context ctx =(Context)initCtx.lookup("java:comp/env");
     DataSource ds =(DataSource)ctx.lookup(dsName);
     conn = ds.getConnection();
     }
     catch(Exception e)
     {
     System.out.print(e.toString());
     }
    }
    public synchronized Statement getStmt()throws Exception
    {
     stmt=conn.createStatement();
     return stmt;
    }
    public synchronized PreparedStatement getPstmt(String sql)throws Exception
    {
     pstmt=conn.prepareStatement(sql);
     return pstmt;
    }
}
我想问问我怎么在另一个JAVABEAN中使用它?我试过这样:
DBConnSource dbc=new DBConnSource;
Statement stmt=dbc.getStmt();
sql="..............";
ResultSet rs=stmt.executeQuery(sql);
可是不管我这个SQL怎么写.都是空指针错误.NULLPOINTEREXECEPTION.
想请教各位高人.我怎么在一个JAVABEAN中使用一个已经定义好的数据源的BEAN.
谢谢!

解决方案 »

  1.   

    你缺个 Connection con = dbc.getConnection()
      

  2.   

    回楼上:
    DataSource ds =(DataSource)ctx.lookup(dsName);
      conn = ds.getConnection();
      }
    这不是写过了吗?
      

  3.   

    DBConnSource dbc=new DBConnSource;这就错了。
    应该是DBConnSource dbc=new DBConnSource(这里是jndi的名字);
      

  4.   

    问题解决了.问题出在我多写了一个Statement stmt=dbc.getStmt();因为上面我已经定义了一个"private Statement stmt" 下面我再这样写Statement stmt=dbc.getStmt().就是我定义了两个Statement 对象,名称都是stmt.这时系统就无法决定执行哪一个stmt.所以这个结果集rs就找不到正确的sql对象.所以会报空指针错误.
    我把"Statement stmt=dbc.getStmt();"改成"stmt=dbc.getStmt();"页面就正常运行了.
    还要请教各位专家,在JAVABEAN中使用到的变量,是不是必须都是事先定义.象我一开始所犯的错误,是不是属于重复定义.谢谢指点.