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

Connecting SQL Server using Java/JDBC


Below program consists of steps to connect SQL server using JDBC

package com.javatutorials;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class SqlServerConnection {
public static Connection connection = null;
public static Connection getDbConnection() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager
.getConnection("jdbc:odbc:mydsn;user=sa;password=sa12$");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}

public static void closeConnection() {
if (connection != null)
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

What is the difference between callable statements, prepare statements , createstatements?


  • CallableStatement: This is used to retrieve the stored procedures from the database. ie., these statements are used when two or more SQL statements are retrieved over and over.
  • PreparedStatement: These are pre-compiled statements which are stored in database. We are using these, if the same query is to be executed over and over.
  • CreateStatement: This is used to execute single SQL statement.