Java 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 same as using SQL Server authentication account. But the only change is that the connection string is changed to: jdbc:odbc:dsn-name. There is no need to use username/password anymore, because it is already connected to the server.
Here is a sample code of a database class which uses this kind of authentiation:
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); } }
You may also like:
Leave a comment
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.
I use sqljdbc4.jar.