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://<IP Address>: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());
}
}

Advertisements
About

I born in Good cultural place called India. My family is traditional family. We fallow all Indian traditions.

Tagged with: , , , , ,
Posted in JDBC

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.

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 678 other followers

Calendar
July 2013
M T W T F S S
« Jun   Aug »
1234567
891011121314
15161718192021
22232425262728
293031  
Mallikarjun Gunda

This is Mallikarjun Gunda, I am working as a software professional. Blogging is my Passion. This blog contains the posts on Java related technologies and programming languages. I am happy to share my knowledge through the blogs.

Blog Stats
  • 280,989 hits
IndiBlogger
malliktalksjava.wordpress.c...
70/100