Below is the sample program to connect to MS SQL Sever using JDBC type 4 driver:
package in.javatutorials; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * @author JavaTutorials.in * */ public class MSSqlDBConnection { /** * initialize the connection object */ private static Connection connection = null; /** * Create the database connection and return the same * * @return connection Connection */ public static Connection getDbConnection() { // if required, below variables can be read from properties file String username = "sqlusr"; String password = "sqlpasswrd"; String connStr = "jdbc:sqlserver://:1433;instanceName=SQLEXPRESS;databaseName=test"; try { Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); connection = DriverManager.getConnection(connStr, username, password); } catch (ClassNotFoundException classNotFoundExcep) { classNotFoundExcep.printStackTrace(); } catch (SQLException sqlExcep) { sqlExcep.printStackTrace(); } return connection; } /** * Close the connection if exists, this method can be called once * transaction is completed, so that it will close the connection */ public static void closeConnection() { if (connection != null) { try { connection.close(); } catch (SQLException sqlExcep) { sqlExcep.printStackTrace(); } } } public static void main(String[] args) { System.out.println("Print the Database conn object : " + getDbConnection()); } }