Skip to content
Advertisement

Java to SQL Server using Windows Authentication

I am trying to connect to a remote SQL Server DB from a Java application without success.

I am able to successfully connect to that SQL Server instance from a SQL client for Mac called SQLPro for MSSQL enter image description here

However, if I try to connect from the Java application using those same credentials, I always get a Login failed error, this is the code snipper I’m using:

String connectionUrl =
        "jdbc:sqlserver://some-host:1433;"
                + "database=DBName;"
                + "user=GLOBAL\user;"
                + "password=somepassword;"
                + "encrypt=true;"
                + "trustServerCertificate=true;"
                + "loginTimeout=30;";

ResultSet resultSet = null;

try (Connection connection = DriverManager.getConnection(connectionUrl);
     Statement statement = connection.createStatement();) {

    // Create and execute a SELECT SQL statement.
    String selectSql = "select * from R2.LABEL_MASTER";
    resultSet = statement.executeQuery(selectSql);

    // Print results from select statement
    while (resultSet.next()) {
        System.out.println(resultSet.getString(2) + " " + resultSet.getString(3));
    }
}
catch (SQLException e) {
    e.printStackTrace();
}

I’m using this gradle dependency for the sql server jdbc driver

implementation group: ‘com.microsoft.sqlserver’, name: ‘mssql-jdbc’, version: ‘10.2.0.jre11’

One important point is that I am not on a Windows machine, which should not be an issue, as I mentioned, I am able to connect to the SQL Server using an SQL client.

Advertisement

Answer

To connect using Windows Auth with app-provided credentials, you must configure the connection to use NTLM. The current connection string is for SQL Auth.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement