Wednesday, February 27, 2013

JDBC Connection for SQL SERVER


 Create two class "JDBCConnector" and "TestConnection" in same package. Replace the values YourServerNameorIp, YourDBInstanceName, YourDBUserName and YourDBPassword with Appropriate values.


This sample code works fine with SQL SERVER 2008,

Kindly let me know if it is not working any of the sql server version.


JDBCConnector.Java


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


public class JDBCConnector {

public JDBCConnector()
{
MakeConnection("YourServerNameorIp", 
"YourDBInstanceName", "YourDBUserName", "YourDBPassword");
}
private void MakeConnection(String strServerIPAddress, 
String strDatabaseName, String strUserName, String strPassword)
{
if(openConnection(strServerIPAddress, 
strDatabaseName, strUserName, strPassword))
{
System.out.println("Test Connection Successful");
}
else
{
System.out.println("Test Connection not succesful");
}
}

private boolean openConnection(String strServerIPAddress, 
String strDatabaseName, String strUserName, String strPassword) {
//String connect to SQL server
String url = "jdbc:sqlserver://" + strServerIPAddress + ":1433" +
";DatabaseName=" + strDatabaseName;

try
{
//Loading the driver... 
Class.forName( "com.microsoft.sqlserver.jdbc.SQLServerDriver" );
}
catch( java.lang.ClassNotFoundException e )
{
System.out.println("ClassNotFoundException");
return false;


try
{
//Building a Connection
Connection m_Conn = DriverManager.getConnection(url, strUserName, strPassword); 
if(m_Conn == null )
return false; 
}
catch( java.sql.SQLException e )
{
System.out.println("Connection error");
return false;

return true; 
}

}

TestConnection.Java


public class TestConnection
{
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
JDBCConnector conn = new JDBCConnector();
}
catch (Exception ex)
{
System.out.println("base class not found");
}
}

}

No comments:

Post a Comment

Please include your thoughts/suggestion to make it as a better blog. If you find it useful, Please update with your valuable comments, so that others can use it.