Sunday, April 12, 2009

Java : JDBC Connection codes in Oracle and MS SQL

Oracle Connection



/* Here is complete code for OracleConnection.java */

import java.sql.*;

public class OracleConnection
{
public static void main(String[] args)
{
//connection
Connection con=null;
ResultSet rs=null;
Statement stmt=null;

try
{
Class.forName("oracle.jdbc.driver.OracleDriver"); //Step 1: Loading Drivers

con = DriverManager.getConnection("jdbc:oracle:thin:@10.10.10.10:8080:vas","username","password"); //Step 2: Making Connection

stmt = con.createStatement(); //Step 3: Creating JDBC Statement

String query = "Select * from EMPLOYEE";

rs = stmt.executeQuery(query); //Step 4: Execute the Ststement

while (rs.next()) //Step 5: Looping through the ResultSet
{
System.out.println(rs.getString(1)+""+rs.getString(2));
}

stmt.close(); //step 6: Close the Connection and Statement
con.close();
rs=null;
stmt=null;
con=null;
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}

MS SQL Connection




/* Here is complete code for MSSQLConnection.java */

import java.sql.*;

public class MSSQLConnection
{
public static void main(String[] args)
{
//connection
Connection con=null;
ResultSet rs=null;
Statement stmt=null;

try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //Step 1: Loading Drivers

con = DriverManager.getConnection("jdbc:sqlserver://10.10.10.10:8080;databaseName=DBNAME;user=scott;password=tiger"); //Step 2: Making Connection

stmt = con.createStatement(); //Step 3: Creating JDBC Statement

String query = "Select * from EMPLOYEE";

rs = stmt.executeQuery(query); //Step 4: Execute the Ststement

while (rs.next()) //Step 5: Looping through the ResultSet
{
System.out.println(rs.getString(1)+""+rs.getString(2));
}

stmt.close(); //step 6: Close the Connection and Statement
con.close();
rs=null;
stmt=null;
con=null;
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}