Thursday, October 17, 2013

Connecting to MS SQLServer from Linux using windows authentication , java and jtds

Download jtds from http://jtds.sourceforge.net

The following example connects to a SQLServer using windows authentication.
Source modified from "Here"

To compile the code use
$ javac testConnection.java

To run the code

$ java -cp ./jtds/jtds.jar:. testConnection

This assumes you have downloaded the jtds into a subfolder called jtds. Also in the code 1433 is the port of SQLServer.


 import java.sql.*;  
 public class testConnection  
 {  
   public static void main(String[] args)  
   {  
     DB db = new DB();   
     db.dbConnect("jdbc:jtds:sqlserver://<your SQL Server>:1433/<DatabaseName>;domain=<your Domain>","UserName","Password");  
   }  
 }  
 class DB  
 {  
   public DB() {}  
   public void dbConnect(String db_connect_string,  
  String db_userid, String db_password)  
   {  
     try  
     {  
       Class.forName("net.sourceforge.jtds.jdbc.Driver");  
       Connection conn = DriverManager.getConnection(  
   db_connect_string, db_userid, db_password);  
       System.out.println("connected");  
     }  
     catch (Exception e)  
     {  
       e.printStackTrace();  
     }  
   }  
 };