0

I am getting No suitable driver found for jdbc:microsoft:sqlserver exception when I comment out first line.

I am using jdbc 4.1 and as https://stackoverflow.com/a/8053125/1379734 explained Class.forName() method is not necessary. What is wrong with my code?

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = java.sql.DriverManager.getConnection(getConnectionUrl(), userName, password);
Community
  • 1
  • 1
hellzone
  • 5,393
  • 25
  • 82
  • 148
  • 3
    Then you aren't using a JDBC4 compatible driver (or at least it isn't adhering to what it should do). The fact that you have a JDK that comes with JDBC 4.x doesn't mean that the driver you have is automatically a JDBC 4.x suitable driver. You will have to use the correct driver as well. – M. Deinum Feb 10 '17 at 13:25
  • It sounds like you are using an invalid URL or a very old driver, a correct JDBC url for SQL Server starts with `jdbc:sqlserver:`, not `jdbc:microsoft:sqlserver`. See also https://learn.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url – Mark Rotteveel Feb 10 '17 at 13:27
  • what version of the sql driver are you using? a compatible version should have a META-INF\services\java.sql.Driver file in it. – Yogesh_D Feb 10 '17 at 13:30

1 Answers1

0

The fact it works when you use Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); and a JDBC URL that starts with jdbc:microsoft:sqlserver indicates you are using the +/- 17 year old Microsoft SQL Server 2000 JDBC driver. This driver predates JDBC 4, so it does not support the driver auto-loading through /META-INF/services/java.sql.Driver.

Since the SQL Server 2005 JDBC driver, the correct class name is com.microsoft.jdbc.sqlserver.SQLServerDriver (note that jdbc and sqlserver switched places) and the URL prefix changed to jdbc:sqlserver: (see also this blogpost). I believe that JDBC 4 autoloading was added in the SQL Server 2008 JDBC driver. See Microsoft JDBC Driver for SQL Server for more information.

If you want to take advantage of the driver auto-loading, you will need to upgrade your driver to a newer version (the latest preferably) and change your configuration.

See: https://github.com/Microsoft/mssql-jdbc and the Microsoft Download Center

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197