JDBC error when connecting Tomcat 5.5 to SQL 2008:

2019-09-08 07:53发布

问题:

I'm attempting to connect a Tomcat 5.5 instance on my workstation (running with Eclipse) to a SQL Express instance on my workstation, and I'm having some connection issues.

I'm getting this exception:

Cannot create JDBC driver of class '' for connect URL 'null'

Here's my META-INF/context.xml:

<Context>
  <Resource name="jdbc/SQLDB" auth="Container"
  type="javax.sql.DataSource" username="AppUser" password="password"
  driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver" 
  url="jdbc:sqlserver://localhost;DatabaseName=AppUser;SelectMethod=cursor;"
  maxActive="8"/>
</Context>

And my WEB-INF/web.xml:

<resource-ref>
  <description>SQL Database Connection</description>
  <res-ref-name>jdbc/SQLDB</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
</resource-ref>

And my source:

InitialContext ic = new InitialContext();
DataSource ds = (DataSource) ic.lookup("java:comp/env/jdbc/SQLDB");
Connection conn = ds.getConnection();

I have also placed the sqljdbc4.jar file into Tomcat's common/lib folder.

Some of the Tomcat documentation references adding items to the server.xml file, and others do not; I don't think that's needed, given that only one webapp will be using the database. What am I missing, here?

回答1:

This is the common mistake that peoples put the jar in tomcat's lib. Remember always put all external jars in your apps lib i.e. YourAppDir>WebContent>WEB-INF>lib

The second thing to do is to recognize the jar in eclipse. do that as follows:

  1. Right click on your project in Eclipse
  2. click on properties.
  3. on properties window click on JavaBuildPath
  4. select Libraries tab
  5. click AddJARs button & add the external jars from your project's lib