The code
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
cannot throw
ClassNotFoundException - com.microsoft.jdbc.sqlserver.SQLServerDriver
as the names are different. Is it possible that you have it set up incorrectly in your code?
I downloaded the sqljdbc41.jar from their website and see that the correct name for the class is com.microsoft.sqlserver.jdbc.SQLServerDriver
.
$ jar tf sqljdbc41.jar | grep SQLServerDriver.class
com/microsoft/sqlserver/jdbc/SQLServerDriver.class
I just found both names on Microsoft's web documentation, so either they renamed this class (changed its package) at some point, or they have errors on some of their docs.
All you should need to do is drop that .jar in Tomcat's lib directory (e.g.apache-tomcat-7.0.67lib
), and restart Tomcat.
If you have the correct class name, and the right jar in the lib directory, and are still seeing that error, I wonder if you have some sort of typo in your eclipse setup, and deploying from eclipse is somehow forcing an attempt to load that broken class name. (I don't use Eclipse, and I don't know about deploying from there).
Try creating a very simple application (and don't tell eclipse about the MS driver class):
@WebServlet("/")
public class SimpleServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Set response content type
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<h1>" + "Welcome to the servlet!" + "</h1>");
try {
String server = "localhost";
String database = "testDB";
String password = "sapassword";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://"+server+":1433;databaseName="+database+";user=sa;password="+password+";";
Connection con = (Connection) DriverManager.getConnection(connectionUrl);
} catch (ClassNotFoundException e) {
out.println("<h2>" + e.getClass().getSimpleName() + "_" + e.getMessage() + "</h2>");
} catch (SQLException e){
out.println("<h2>" + e.getClass().getSimpleName() + "_" + e.getMessage() + "</h2>");
} finally {
out.println("<h1>" + "That's the end of the servlet!" + "</h1>");
}
}
}
And running it. If you see output like:
Welcome to the servlet!
SQLServerException_The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
That's the end of the servlet!
It means that the driver loaded properly. The connection failed b/c I don't have SQLServer instance currently running to test against.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…