Connect to MS SQL Server using JDBC

The following example shows a java class that can be used to verify if you connection to MS SQL Server using JDBC is working properly. The following code establishes a connection to MS SQL server and then executes a query to print system tables. You need to get Microsoft’s JDBC drivers or jTDS JDBC drivers.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
 
public class ConnectMSSQLServer
{
   public void dbConnect(String db_connect_string,
            String db_userid,
            String db_password)
   {
      try {
         Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
         Connection conn = DriverManager.getConnection(db_connect_string,
                  db_userid, db_password);
         System.out.println("connected");
         Statement statement = conn.createStatement();
         String queryString = "select * from sysobjects where type='u'";
         ResultSet rs = statement.executeQuery(queryString);
         while (rs.next()) {
            System.out.println(rs.getString(1));
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
 
   public static void main(String[] args)
   {
      ConnectMSSQLServer connServer = new ConnectMSSQLServer();
      connServer.dbConnect("jdbc:sqlserver://<hostname>", "<user>",
               "<password>");
   }
}

Change <hostname>, <user> and <password> to the correct values. Also, if you use the jTDS drivers, the driver class should be set to net.sourceforge.jtds.jdbc.Driver.

One Reply to “Connect to MS SQL Server using JDBC”

Leave a Reply

Your email address will not be published. Required fields are marked *