我正在使用下面的代码从 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()