JDBC Type Driver connection for MS SQL Server


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());
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.