1

I am trying to connect to a MS SQL Server database running on the same machine as the application but I keep getting the error:

No suitable driver found for jdbc:sqlserver://localhost:1433;database=SQLTEST;user=TEST;password=1234567890;encrypt=true;trustServerCertificate=false;loginTimeout=30;

I am running MS SQL Server 2017 and JDK1.8.x.

The first thing I did was creating a user in the following way in SSMS using T-SQL:

USE SQLTEST
CREATE ROLE TEST
GRANT SELECT, INSERT ON SCHEMA :: [dbo] TO TEST
CREATE LOGIN TEST_LOGIN WITH PASSWORD = '1234567890'
CREATE USER USER_TEST FROM LOGIN TEST_LOGIN
ALTER ROLE TEST ADD MEMBER USER_TEST

I then used Maven to add the driver to my project in the pom.xml file:

<!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc -->
<dependency>
     <groupId>com.microsoft.sqlserver</groupId>
     <artifactId>mssql-jdbc</artifactId>
     <version>7.2.2.jre8</version>
</dependency>

Followed by adding and altering the example code given by Microsoft (note that this should become a JAX-RS REST-API, that is why the annotations are there):

@Path("t2")
public class T2 {
    @GET
    public String show() {
        String r = "";
        String connectionUrl =
                "jdbc:sqlserver://localhost:1433;"
                        + "database=SQLTEST;"
                        + "user=TEST;"
                        + "password=1234567890;"
                        + "encrypt=true;"
                        + "trustServerCertificate=false;"
                        + "loginTimeout=30;";

        try (Connection connection = DriverManager.getConnection(connectionUrl);) {
            // Code here.
        }
        // Handle any errors that may have occurred.
        catch (SQLException e) {
            e.printStackTrace();
            r = e.getMessage();
        }
        return r;
    }
}

Running this results in the error as given in the start of this post. Did I forget something or did I do something wrong?

Ruud Verhoef
  • 1,687
  • 8
  • 26
  • You shouldn't use `DriverManager` directly in a web application, instead use a data source with a connection pool (eg Apache DBCP, HikariCP, etc). The problem is you need to explicitly load the driver if the driver is deployed within a web application (automatic driver loading only works for drivers on the main classpath, not on a web application specific classpath). – Mark Rotteveel Apr 20 '19 at 10:35

1 Answers1

1

Looks similar to this issue:

java.sql.SQLException: No suitable driver found for jdbc:sqlserver

Doesnt look like you've got Class.forName("xxxx"); before your DriverManager.getConnection section in the try statement.

mvee
  • 241
  • 1
  • 13
  • With these newer versions of jdbc, 7.2.2.jr8, I don't think you need to use Class.forName any longer. I'm surprised this was accepted as the right answer. – djangofan Jun 03 '20 at 23:21