Home > Uncategorized > Connect to Microsoft #SQL server using #Java and Windows Authentication.

Connect to Microsoft #SQL server using #Java and Windows Authentication.

java-sql-server-connect-01

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;

https://github.com/infiniteloopltd/SQLJava

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.

 

 

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: