Thursday, May 29, 2014

Accessing MS SQL Server with JDBC Driver with Windows Authentication - Java Eclipse

Today I will show you how to connect to a MS SQL Server using the JDBC driver provided by Microsoft. This also comes with sqljdbc_auth.dll which is needed.

Create a new Java project in Eclipse.

Create a folder named 'lib' under the project directory and copy over sqljdbc_auth.dll and sqljdbc4.jar into lib.

Add sqljdbc4.jar to your build path. Under Properties > Java Build Path > Libraries Tab, expand the jar file and edit the native library location to the folder where you downloaded the sqljdbc_auth.dll. (.../Microsoft JDBC Driver 4.0 for SQL Server/sqljdbc_4.0/enu/auth/(x64 or x86).

This is how to connect to the database from Java.

public void readDataBase() throws Exception {
     try {
       final String SERVER_NAME = "Name of the server.";
    final String USER = "Windows account. Include the domain.";
    final String PW = "";
    final String URL = "jdbc:sqlserver://" + SERVER_NAME +";integratedSecurity=true;";
       // this will load the MySQL driver, each DB has its own driver. Keep as is.
              Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
       // setup the connection with the DB.
       connect = DriverManager
           .getConnection(URL, USER, PW);

       // statements allow to issue SQL queries to the database
       statement = connect.createStatement();
       // resultSet gets the result of the SQL query
       resultSet = statement
           .executeQuery("query goes here");
       writeResultSet(resultSet);
       writeMetaData(resultSet);
     } catch (Exception e) {
       throw e;
     } finally {
       close();
     }
     close();
   }

This is an example of reading the table info.

private void writeMetaData(ResultSet resultSet) throws SQLException {
     // now get some metadata from the database
     System.out.println("The columns in the table are: ");
     System.out.println("Table: " + resultSet.getMetaData().getTableName(1));
     for  (int i = 1; i<= resultSet.getMetaData().getColumnCount(); i++){
       System.out.println("Column " +i  + " "+ resultSet.getMetaData().getColumnName(i));
     }
   }

And reads the data from the table.


private void writeResultSet(ResultSet resultSet) throws SQLException 
{
     //read by row
     while (resultSet.next()) {
       String column = resultSet.getString("column name");
       System.out.println(column);
     }
}

No comments:

Post a Comment