Posted on 2006-07-04 13:28
天空蒼茫 閱讀(1669)
評論(0) 編輯 收藏 所屬分類:
eclipse
首先創(chuàng)建weblogic數(shù)據(jù)源。
創(chuàng)建一個javabean取得數(shù)據(jù)源中的連接CONN
代碼:
/**
?* 程序開發(fā)日期:2006-6-28-16:09:14
?* javaworker.cn中程序員:葉明開發(fā)
?* 程序作用:從連接池中取出一條記錄,使用創(chuàng)建數(shù)據(jù)庫連接,以及釋放該連接
?* 程序開發(fā):
?*/
package com.javawoker.yeming.jiemie.database;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import org.apache.log4j.Logger;
/**
?*@author 葉明 ---guming123416@gmail.com
?*@version $Id: v 1.01 2006/06/38 16:09:14 teodord Exp $
?*/
public class Pubconn {
?
?/*
? * 創(chuàng)建私有變量conn為數(shù)據(jù)庫連接對象中Connection
? * 創(chuàng)建私有變量dsye為數(shù)據(jù)庫連接池的DataSource
? */
?
?private Connection conn;
?private DataSource dsye;
?private static Logger log=Logger.getLogger(Pubconn.class);
?/*
? * 創(chuàng)建構(gòu)造函數(shù)Pubconn,在建立class中加載數(shù)據(jù)源的InitialContext
? */
?public Pubconn()
?{
??try{
???Context initCtx=new InitialContext();
???if(initCtx==null)
???{
????throw new Exception("不能加載文件Context");
???}
???dsye=(javax.sql.DataSource)initCtx.lookup("jdbc/yeming");
??}catch(Exception ex)
??{
???ex.printStackTrace();
???log.error("在加栽數(shù)據(jù)庫連接池時間發(fā)生錯誤"+ex.getMessage());
??}
?}
?/*
? * 從連接池中取出一條連接變量
? *
? */
?public Connection getConn()
?{
??try{
???conn=dsye.getConnection();
??}catch(SQLException ex)
??{
???ex.printStackTrace();
???log.error("獲得連接對象CONN時間發(fā)生錯誤"+ex.getMessage());
??}
??return conn;
?}
?/*
? * 關(guān)閉數(shù)據(jù)庫連接,釋放資源
? */
?public void closeConn(Connection conn)
?{
??try{
???if(conn!=null)
???{
????conn.close();
????conn=null;
???}
??}catch(SQLException ex)
??{
???ex.printStackTrace();
???log.error("關(guān)閉CONN時間發(fā)生錯誤"+ex.getMessage());
??}
?}
}
然后建立調(diào)用頁面
代碼如下:
<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="GBK" contentType="text/html charset=gbk"%>
<jsp:useBean id="yeconn" scope="page" class="com.javawoker.yeming.jiemie.database.Pubconn"></jsp:useBean>
<%
Connection conn=yeconn.getConn();
Statement stmt=conn.createStatement();
String sql="select * from combasicinfo";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
? out.println(rs.getInt(1));
? out.println(rs.getString(2));
}
rs.close();
stmt.close();
yeconn.closeConn(conn);
%>