Friday, January 28, 2011

Connecting SQL Server using Windows Authentication

Connecting SQL Server using Windows Authentication


Step 1: Setup ODBC


To set up ODBC
a. goto Control Panel
b.Double click on "Administrative Tools"
c. Double click on "Data Sources (ODBC)"
d. Under "User DSN" tab, click on "Add" button
e. In "Create New Data Set" window, select "SQL Native Client"
f. In "Create a New Data Source to SQL Server" window, enter data source name, select your db server for which you want to connect from the "Server" drop down list
g. Click on "Next" button
h. In the next window, select the 1st option i.e., "With Integrated Windows authentication", click on "Next" button
i. Click on "Finish" button


This newly added data source should be available for you.


Step 2: Adding "sqljdbc4.jar" file


Add "sqljdbc4.jar file to your project library.

Step 3: Write the following Class to connect DB

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 dataSourceName){
this.dbName = dbName;
try{
      class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
       this.conn = DriverManager.getConnection(dataSourceName)
      System.out.println("Connected Successfully");
     }

catch(ClassNotFoundException e){
e.printStackTrace();
}

catch(SQLException e){
e.printStackTrace();
}
}

Step 4:  Execute it from Main Method:

import java.sql.*;

public class Main{

public static void main(String[] args)
{
try{
     Database db = Database("SQLEXPRESS", "jdbc:odbc:MySQLDB");
     }
catch(Exception e){
e.prntStackTrace();
}

Output: Connected Successfully