关闭

jdbc连接池

标签: jdbcexceptionsqlserverlistimportstring
274人阅读 评论(0) 收藏 举报

------------------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
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:22031次
    • 积分:202
    • 等级:
    • 排名:千里之外
    • 原创:43篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档