使用TOMCAT的连接池的问题。
我想用封装好的serverlet访问TOMCAT连接池,但是serverlet中的JAVA代码怎么才能得到连接池的信息。
代码如下
DBConnection.java
---------------------------------
import java.sql.Connection;
import
java.sql.SQLException;
import java.sql.DriverManager;
import javax.naming.InitialContext;
import javax.naming.Context;
import javax.naming.*;
import javax.sql.DataSource;
import java.util.Properties;
import java.util.HashMap;
public class DBConnection {
public Context initctx = null,ctx=null;
public Connection con=null;
public Object obj=null;
private DataSource ds=null;
public DBConnection()
{
try
{
initctx=new InitialContext();
ctx = (Context)initctx.lookup( "java:comp/env "); <---这句怎么找到Context?
obj = (Object) ctx.lookup( "jdbc/szoracle ");
javax.sql.DataSource ds=(javax.sql.DataSource)obj;
}
catch (NamingException ex)
{
ex.printStackTrace();
System.out.println(ex);
}
}
public Connection getConnection()
{
try
{
con=ds.getConnection();
}
catch (
SQLException ex)
{
//ex.printStackTrace();
if(con==null)
System.out.println( "con is null! ");
System.out.println(ex);
}
return con;
}
}
------解决方案--------------------数据库连接池封装很简单就的,用JNDI几句话搞定:
import javax.sql.*;
import javax.naming.*;
import java.sql.*;
public class DBconnection {
DataSource ds=null;
Connection conn=null;
public DBconnection()
{
}
public Connection getConnection()
{
try
{
Context initCtx=new InitialContext();
Context envCtx=(Context)initCtx.lookup( "java:comp/env ");
ds=(DataSource)envCtx.lookup( "jdbc/login ");
conn=ds.getConnection();
return conn;
}
catch(Exception e)
{
System.out.println(e.getStackTrace());
return null;
}
}
}
------解决方案--------------------注意你的代码
public DBConnection()
{
try
{
initctx=new InitialContext();
ctx = (Context)initctx.lookup( "java:comp/env "); <---这句怎么找到Context?
obj = (Object) ctx.lookup( "jdbc/szoracle ");
javax.sql.DataSource ds=(javax.sql.DataSource)obj;
}
catch (NamingException ex)
{
ex.printStackTrace();
System.out.println(ex);
}
}
这个ds是局部变量
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <