package test;
import java.sql.*;
import javax.naming.*;
import javax.sql.DataSource;

/**
 * @author huangqin
 *
 */
public class DBConn {
 public static synchronized Connection getConnection() throws Exception{
  try{
   Context initCtx=new javax.naming.InitialContext();//获取JNDI初始上下文对象
   //在JNDI命名空间java:comp/env段里获得上下文对象
   Context envCtx=(Context)initCtx.lookup("java:comp/env");
   DataSource ds=(DataSource)envCtx.lookup("jdbc/xscj");
   return ds.getConnection();
  }catch(SQLException e){
   throw e;
  }catch(NamingException ex){
   throw ex;
  }
 }

}

package test;
import java.sql.*;
import test.DBConn;
/**
 * @author huangqin
 *
 */
public class DBResult {

 private Connection con;
 public DBResult() throws Exception{//一定要抛出异常,否则报错
  this.con=DBConn.getConnection();
 }
 public ResultSet getResult(String sql){
  try{
   Statement stmt=con.createStatement();
   ResultSet rs=stmt.executeQuery(sql);
   return rs;
  }catch(Exception e){
   return null;
  }
 }
 public void doExecute(String sql){
  try{
   Statement stmt=con.createStatement();
   stmt.executeQuery(sql);
  }catch(Exception e){}
 }
 public PreparedStatement getPreparedStatement(String sql){
  try{
   PreparedStatement pstmt=con.prepareStatement(sql);
   return pstmt;
  }catch(Exception e){
   return null;
  }
 }
 public void closeConn(){
  try{
   this.con.close();
  }catch(Exception e){
   e.printStackTrace();
  }
 }
}