Connect to Microsoft #SQL server using #Java and Windows Authentication.
This post outlines how to connect to a local instance of SQL server using Windows Authentication from Java.
TLDR; Here’s the github repo for anyone who wants the source;
This download assumes you are running JRE8 and on a 64 bit machine, if you have a different configuration, then this may not work, but assuming you are, then just download those files from the Github repo.
The code is as follows;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;public class SQLJava {
public static void main(String[] args) {
String dsn = “jdbc:sqlserver://localhost;databaseName=Library;integratedsecurity=true”;
try {
Connection conn = DriverManager.getConnection(dsn);
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(“select * from students”);
while (result.next()) {
String firstname = result.getString(“Firstname”);
String surname = result.getString(“Surname”);
System.out.println(firstname + ” ” + surname);
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
and to run this, you need
javac SQLJava.java
java -cp “.;sqljdbc42.jar” SQLJava
Note the inclusion of the -cp (classpath) switch, to ensure that the JDBC driver is included. You should also have the DLL sqljdbc_auth.dll in the same folder, otherwise this will only work with SQL authentication.