tomcat+SQL server2000数据连接池的问题??
代码:
package com.yl.test;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class DBUtil {
public static void main(String[] args) throws Exception
{
DataSource ds = null;
Context ctx = new InitialContext();
System.out.println( "0000000000000000 ");
if(ctx==null)
{
throw new Exception( "no context ");
}
else
ds=(DataSource) ctx.lookup( "java:comp/env/jdbc/test ");
System.out.println( "1111111111111 ");
Connection con=ds.getConnection();
Statement st=con.createStatement();
ResultSet rs=st.executeQuery( "select * from TABLE1 ");
while(rs!=null)
{
System.out.println( "name== "+rs.getString( "name "));
}
rs.close();
st.close();
con.close();
}
}
报错
Exception in thread "main "
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.lookup(Unknown Source)
at com.yl.test.DUtil. <init> (DUtil.java:19)
at com.yl.test.DUtil.main(DUtil.java:56)
各位英雄,帮忙看看在线等待啊,汗!
------解决方案--------------------給一段例子你看看:
public Connection getConnectionByDBPool() {
Connection conn = null;
Context initCtx = null;
Object obj = null;
try {
initCtx = new InitialContext();
if(initCtx==null){
throw new Exception( "没有匹配的环境 ");
}
switch(DBServer) {
case 0: //tomcat
Context ctx = (Context) initCtx.lookup( "java:comp/env ");
obj = (Object) ctx.lookup(jndi_Name);
break;
case 1: // jboss
String jndi_name= "java:/ " + jndi_Name;
obj = (Object) initCtx.lookup(jndi_name);
break;
case 2: //weblogic
obj = (Object) initCtx.lookup(jndi_Name);
break;
}
DataSource ds = (javax.sql.DataSource)obj;
if (ds==null) {
throw new Exception( "没有匹配的数据库 ");
}
conn = ds.getConnection();
} catch (Exception e) {
e.printStackTrace();
}