Saturday, October 13, 2012

How to use JDBC to connect with SQL Server with Windows Authentication

Recently, I am working on a project that requires to data into database. Since I already have Microsoft SQL Server 2008R2 installed locally, I would like to use Java gather data from the web and store it in SQL Server.

The only one thing that are required is the JDBC driver. You can download it here. Download it in any format. You will have to unzip it eventually. Then you will get the following tree structure:


The sqljdbc4.jar is the Java library that you need to specify it inside your Java IDE (eg. Eclipse). One way of doing that is to right click the project name and navigate to Build Path --> Configure Build Path...


In the following window, click Add External JARs and select the sqljdbc4.jar in your downloaded file.


Once have that library in your Java project, you can import the library and write the Java code to connect to the database.

If you are using the SQL Server Authentication, the following code will work perfectly:



However, this article is to point out the important fact that you need to pay attention when you are using Windows Authentication for SQL Server.


  • First, you don't have to specify the username and password. Instead, you should use integratedSecurity=true parameter.
  • Second, you have to copy the sqljdbc_auth.dll file to your project root directory.

The code will look like this:




The sqljdbc_auth.dll is located inside the auth folder in your downloaded driver. Copy and paste that dll file into your project root directory.

Then everything works fine!