java – Error for sqlServer JDBC Import with Maven

Question:

In my java web application, I needed to add a connection to a sql server database, so I put it as a maven dependency as described below:

<dependency>
        <groupId>com.microsoft.sqlserver</groupId>
        <artifactId>mssql-jdbc</artifactId>
        <version>6.4.0.jre8</version>
        <scope>compile</scope>
    </dependency>

The dependency has been downloaded and is located in the m2 folder.

Running the application locally on my machine, everything works with the import code below:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import com.microsoft.sqlserver.jdbc.SQLServerDriver;

However, after generating the project WAR with the mvn clean package -DskipTests -Pdev and published inside a development server, I get the following error:

Root cause of ServletException. java.lang.NoClassDefFoundError: com/microsoft/sqlserver/jdbc/SQLServerDriver

I believe either I'm importing wrong in the code or I forgot to configure something for maven.

I also verified that after running the maven command the dependency is placed inside WEB-INF\lib according to the other dependencies, but my application doesn't find it, can someone help me?

Answer:

I have experienced this same problem in the past and resolved it as follows:

Add the code below to your connection code:

static {
    try {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    } catch (ClassNotFoundException e) {
        System.err.println("SQLServer DataSource unable to load SQLServer Driver");
    }
}
Scroll to Top