以前没用过jdni的连接,今天在网上找了些资料,试着连了下,不成功!请各位高手看看,谢谢!
我用的tomcat6.0+sqlserver2005我的tomcat中的context.xml文件中加入了
<Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource" 
  driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver"  
  url="jdbc:sqlserver://10.78.28.93:1433;DatabaseName=OSWorkflow"  
  username="sa" 
  password="xyk"
  maxActive="10" 
  maxIdle="3" 
  maxWait="10000" /> 
项目中的web.xml文件加入了
<resource-ref>
<description>JNDI test</description>
<res-ref-name>test</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>我的测试代码是
public void connection() {
Connection conn = null;
Context ctx;
try {
ctx = new InitialContext();
Context envCtx = (Context) ctx.lookup("java:comp/env"); 
DataSource ds = (DataSource) envCtx.lookup("jdbc/test"); 
conn = ds.getConnection();
System.out.println("数据库连接成功!");
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}运行代码报错信息是:
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.home.flow.test.JNDI.connection(JNDI.java:21)
at com.home.flow.test.JNDI.main(JNDI.java:43)
Exception in thread "main" java.lang.NullPointerException
at com.home.flow.test.JNDI.connection(JNDI.java:33)
at com.home.flow.test.JNDI.main(JNDI.java:43)

解决方案 »

  1.   

    driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver"  
    应该是这个包没有包含好。。
    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 
    看下这里意思
      

  2.   

    哎,问题解决了!
    错误的原因我都不好意思说,我在main函数里进行测试连接,是取不到tomcat的配置的!
    ~_~!!!!