Java connect MS SQL Server using windows authentication

To connect MS SQL Server using windows authentication, the first step is to setup ODBC. You can go to Control panel -> Administrative tools -> ODBC. Add a new DSN to connect MS SQL Server using windows authentication account following wizard setup.

The second step is the similar with using SQL Server authentication. The only change is that the connection string is: jdbc:odbc:dsn-name. There is no need to use username/password any longer, because it is already connected to the server!

Here is a sample code of a database class which uses windows authentication:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
public class Database {
	public Connection conn = null;
	private String dbName = null;
 
	public Database(){
	}
 
	public Database(String dbName, String dbURL){
		this.dbName = dbName;
		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			this.conn = DriverManager.getConnection(dbURL);//here put the new simple url.
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
 
	public ResultSet runSql(String sql) throws SQLException {
		Statement sta = conn.createStatement();
		return sta.executeQuery(sql);
	}
 
}

The jar file can be downloaded here: http://dev.mysql.com/downloads/connector/j/

Category >> Database  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. clement on 2009-11-23

    Hi, great post !
    Btw, which driver did you use ? I tried with sqljdbc.jar but it didn’t work. Only jdbc:sqlserver urls seem to work …

    Thx.

  2. admin on 2010-5-26

    I use sqljdbc4.jar.

  3. Unnikrishnan P on 2012-2-29

    Hi the post was very helpful. Can you please provide the sqljdbc jar you are using.

  4. eric on 2014-6-1

    and how do i find out the dburl?

  5. Abraham Janne on 2014-10-20

    jdbc:odbc:dsn-name

Leave a comment

*