jdbc连接池

    技术2022-06-30  65

    ------------------1.配置context.xml 文件-----------------

      <Resource name="jdbc/restrant" auth="Container" type="javax.sql.DataSource"  maxActive="100" maxIdle="30" maxWait="10000" username="sa" password=""  driverClassName="net.sourceforge.jtds.jdbc.Driver" url="jdbc:jtds:sqlserver://localhost:1433/restrant" />

    </Context>

    --------------------------------

    package ch06.jndi; import java.sql.*;import java.util.ArrayList;import java.util.List;import Dao.*;import ch03.FoodBean;import javax.naming.*;import javax.sql.*;/* * 使用连接池获取数据库连接 */ public class GetDataBean extends baseDao{  PreparedStatement pstmt;  Connection con;  ResultSet rs;  int num=0;  List foods;    //返回餐品列表  public List getFoods() {     List list =new ArrayList();     Context ctx;     String sql="select * from  dbo.foodInfo";     try {    ctx = new InitialContext();       DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/restrant");       con= ds.getConnection();       pstmt=con.prepareStatement(sql);    rs=pstmt.executeQuery();    while (rs.next()) {       FoodBean foodBean=new FoodBean();       foodBean.setFoodID(rs.getString("foodID"));//餐品编号       foodBean.setFoodName(rs.getString("foodName"));//餐品名称       foodBean.setRemark(rs.getString("remark"));//餐品原料       foodBean.setFoodPrice(rs.getString("foodPrice"));//餐品价格        foodBean.setFoodImage(rs.getString("foodImage"));//餐品图片       foodBean.setDescription(rs.getString("description"));//餐品介绍       list.add(foodBean);    }   } catch (Exception e) {    e.printStackTrace();   }finally   {    this.closeAll(pstmt, con, rs);//调用baseDao   }     return list;     }

      public void setFoods(List foods) {   this.foods = foods;  }

           public FoodBean getFoodByID(String id)  {   Context xts;    FoodBean foodBean=new FoodBean();    String sql="select * from  dbo.foodInfo where foodID="+id;    try {    xts=new InitialContext();    DataSource ds=(DataSource) xts.lookup("java:comp/env/jdbc/restrant");    con=ds.getConnection();    pstmt=con.prepareStatement(sql);   rs=pstmt.executeQuery();   if (rs.next()) {      foodBean.setFoodID(rs.getString("foodID"));//餐品编号      foodBean.setFoodName(rs.getString("foodName"));//餐品名称      foodBean.setRemark(rs.getString("remark"));//餐品原料      foodBean.setFoodPrice(rs.getString("foodPrice"));//餐品价格       foodBean.setFoodImage(rs.getString("foodImage"));//餐品图片      foodBean.setDescription(rs.getString("description"));//餐品介绍   }  } catch (Exception e) {   e.printStackTrace();  }finally  {   this.closeAll(pstmt, con, rs);  }    return foodBean;  } }


    最新回复(0)