我使用下面的代码从servlet连接到SQL Server 2005数据库。但它抛出了以下异常:
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
代码段:
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class InsertServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
doGet(request,response);
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
EmpDetailBean empdetailbean=new EmpDetailBean();
Connection con=null;
PreparedStatement pstmt2=null;
//ResultSet rs=null;
String employeecode=request.getParameter("employeecode");
pw.println(employeecode);
empdetailbean.setEmployeecode(employeecode);
try
{ //String emp_code=(String)session.getAttribute("empcode");
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//String url = "jdbc:sqlserver://localhost;" +
// "databaseName=test;user=sa;password= ;";
//con=DriverManager.getConnection("Jdbc:Odbc:leave1");
con=DriverManager.getConnection("jdbc:sqlserver://10.217.7.3;databaseName=test;user=sa;password=123;");
String query1="insert into leavetype(dbo.empcode) values(?)";
pstmt2=con.prepareStatement(query1);
pstmt2.setString(1,empdetailbean.getEmployeecode());
int k=pstmt2.executeUpdate();
System.out.println(k);
pstmt2.close();
}
catch(Exception e)
{ pw.println("exception"+ e);
}
}
}
日志文件显示
May 2, 2012 11:34:19 AM org.apache.catalina.core.ApplicationContext log
INFO: ContextListener: contextInitialized()
May 2, 2012 11:34:19 AM org.apache.catalina.core.ApplicationContext log
INFO: SessionListener: contextInitialized()
答案 0 :(得分:1)
如果您想使用com.microsoft.sqlserver.jdbc.SQLServerDriver
作为驱动程序,则需要sqljdbc.jar
存在于类路径中WEB-INF\lib
。
如果您想使用Jtds驱动程序请查看此link以获取驱动程序和数据库URL
答案 1 :(得分:0)
似乎已部署的war文件中缺少JDBC连接的Jar文件。你能否确保lib文件正好与war文件一起打包