[java] com.microsoft.sqlserver.jdbc.SQLServerDriver not found error

I am trying to connect to my SQL Server 2008 database from Java and I'm having the same problem from this thread.

String userName = "xxxx";
String password = "xxxx";
String url = "jdbc:sqlserver:xxx.xxx.xxx.xxx;databaseName=asdfzxcvqwer;integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection(url, userName, password);

I keep getting a ClassNotFoundException Whenever I try to load the driver from Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1713)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1558)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at repositories.RepositoryBase.<init>(RepositoryBase.java:22)
    at repositories.ProductsRepository.<init>(ProductsRepository.java:13)
    at api.Products.init(Products.java:31)
    at javax.servlet.GenericServlet.init(GenericServlet.java:160)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193)
    at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:865)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:136)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

I've made sure the necessary jdbc and jtds drivers are added to the library and CLASSPATH is set as well. I'm honestly not sure what went wrong here.enter image description here

Edit: Upon suggestion, I tried to download this jdbc jar and place it in my WEB-INF/lib, then set my CLASSPATH variable to that location. Still, the same problem is happening.enter image description here

Edit2: Never mind, completely reinstalling Eclipse made it work. This is pretty frustrating...

This question is related to java sql-server eclipse jdbc

The answer is


here is your answer

String userName = "xxxx";
    String password = "xxxx";
    String url = "jdbc:sqlserver:xxx.xxx.xxx.xxx;databaseName=asdfzxcvqwer;integratedSecurity=true";

    try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            connection = DriverManager.getConnection(url, userName, password); 

  } catch (Exception e)
  {
     e.printStackTrace();
  }

You are looking at sqljdbc4.2 version like :

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

but, for sqljdbc4 version statement should be:

Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");

I think if you change your first version to write the correct Class.forName , your application will run.


For me it was a wrong maven dependency deceleration, so here is the correct way:

for sqljdbc4 use: sqljdbc4 dependency

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>sqljdbc4</artifactId>
    <version>4.0</version>
</dependency>

for sqljdbc42 use: sqljdbc42 dependency

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>sqljdbc42</artifactId>
    <version>6.0.8112</version>
</dependency>

intellij idea 2019

  1. Download Microsoft JDBC Driver for SQL Server

(https://docs.microsoft.com/en-us/sql/connect/jdbc/download-microsoft-jdbc-driver-for-sql-server?view=sql-server-2017)

  1. Unpack ("C:\opt\sqljdbc_7.2\enu\mssql-jdbc-7.2.2.jre11.jar")
  2. Add; (File->Project Structure->Global Libraries)
  3. Use; (Adding Jar files to IntellijIdea classpath (look video)) add import com.microsoft.sqlserver.jdbc.SQLServerDriver; enter image description here https://youtu.be/-2hjxoRKsyk

or ub Gradle set "compile" compile group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '7.2.2.jre11'


For me it worked after manually copying the sqljdbc4-2.jar into WEB-INF/lib folder. So please have a try on this too.


For me, it worked once I changed

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

to:

in POM

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>6.1.0.jre8</version>
</dependency>

and then:

import com.microsoft.sqlserver.jdbc.SQLServerDriver;

...

DriverManager.registerDriver(SQLServerDriver());    
Connection connection = DriverManager.getConnection(connectionUrl); 

public static final String URL = "jdbc:sqlserver://localhost:1433;databaseName=dbName";
public static final String USERNAME = "xxxx";
public static final String PASSWORD = "xxxx";

/**
 *  This method
    @param args     command line argument
*/
public static void main(String[] args)
{
   try
   {
        Connection connection;
        DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());   
        connection = DriverManager.getConnection(MainDriver.URL,MainDriver.USERNAME,
                        MainDriver.PASSWORD);
        String query ="select * from employee";
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery(query);
        while(resultSet.next())
        {
            System.out.print("First Name: " + resultSet.getString("first_name"));
            System.out.println("  Last Name: " + resultSet.getString("last_name"));                
        }
   }catch(Exception ex)
   {
        ex.printStackTrace();
   }
}

You dont need both jTDS and JDBC in your classpath. Any one is required. Here you need only sqljdbc.jar.

Also, I would suggest to place sqljdbc.jar at physical location to /WEB-INF/lib directory of your project rather than adding it in the Classpath via IDE. Then Tomcat takes care the rest. And also try restarting Tomcat.

You can download Jar from : www.java2s.com/Code/JarDownload/sqlserverjdbc/sqlserverjdbc.jar.zip

EDIT:

As you are supplying Username and Password when connecting,

You need only jdbc:sqlserver://localhost:1433;databaseName=test, Skip integratedSecurity attribute.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to sql-server

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd

Examples related to eclipse

How do I get the command-line for an Eclipse run configuration? My eclipse won't open, i download the bundle pack it keeps saying error log strange error in my Animation Drawable How to uninstall Eclipse? How to resolve Unable to load authentication plugin 'caching_sha2_password' issue Class has been compiled by a more recent version of the Java Environment Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9 "The POM for ... is missing, no dependency information available" even though it exists in Maven Repository The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. on deploying to tomcat

Examples related to jdbc

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver' Hibernate Error executing DDL via JDBC Statement Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment] MySQL JDBC Driver 5.1.33 - Time Zone Issue Spring-Boot: How do I set JDBC pool properties like maximum number of connections? Where can I download mysql jdbc jar from? Print the data in ResultSet along with column names How to set up datasource with Spring for HikariCP? java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why? java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname