日期:2014-05-16  浏览次数:20391 次

Tomcat 5.5下面配置jndi数据库连接池(oracle 9i)

?

Tomcat 5.5下面配置jndi数据库连接池(oracle 9i)

?

public class DataSourceFactory {
?
//?在Tomcat目录下面的conf目录下面修改context.xml文件如下
/*?
? <Context reloadable="true" >
? <!-- name属性中的值要与java类中的datasoruce中的相同,这个可以自己定义更改为不同的值-->
?<Resource name="jdbc/mydb" auth="Container"
??type="javax.sql.DataSource" maxActive="100" maxIdle="30"
??maxWait="10000" username="12500" password="12500"
??driverClassName="oracle.jdbc.driver.OracleDriver"
??url="jdbc:oracle:thin:@192.168.1.115:1521:ORACLE9I" />ORACLE9I是你所连接数据库的服务名(常用的是orcl)
</Context>
*/
//?
//?
?
?private static final String DATASOURCE = "jdbc/mydb";

//"jdbc/mydb"与context.xml中的name值要相同

?public static Connection getConncetion() {
??Connection conn = null;
??try {
???Context ctx = new InitialContext();
???Context env = (Context) ctx.lookup("java:comp/env");
???DataSource ds = (DataSource) env.lookup(DATASOURCE);
???conn = ds.getConnection();
??} catch (SQLException e) {
???// TODO Auto-generated catch block
???e.printStackTrace();
??} catch (NamingException e) {
???// TODO Auto-generated catch block
???e.printStackTrace();
??}
??return conn;
?}
?public static void testJNDI()
?{
??Connection conn=getConncetion();
??try {
???Statement st=conn.createStatement();
???String sql="select * from BIGTYPE";
???ResultSet rs=st.executeQuery(sql);
???while(rs.next())
???{
????System.out.println(rs.getInt(1)+"/t"+rs.getString(2)+"/t"+rs.getString(3));
???}
???conn.close();
??} catch (SQLException e) {
???// TODO Auto-generated catch block
???e.printStackTrace();
??}
?}
}

用main()方法是不能测试的,只有在web环境下才可以成功。

?

?