
REQ for connection b/w jdbc and oracle database

The Java classes to connect to Oracle are contained in the Oracle JDBC driver jar file. For recent releases, these are numbered based on the Java version they are compiled for, such as ojdbc14.jar (for Java 1.4), ojdbc15.jar (for Java 1.5), etc. These drivers can be freely downloaded from Oracle's site (free registration is required).
You can tell the Oracle driver which method you want to use to connect to the database (OCI or Thin) through the JDBC connection URL.
Here are some connection URL formats:
Oracle JDBC Thin Driver Formats:
1)Oracle JDBC Thin using a Service Name:
jdbc:oracle:thin:@//<host>:<port>/<service_name>
2)Oracle JDBC Thin using an SID:
jdbc:oracle:thin:@<host>:<port>:<SID>
3)Oracle JDBC Thin using a TNSName:
jdbc:oracle:thin:@<TNSName>
Oracle JDBC OCI Driver Format
jdbc:oracle:oci:@
Follow these steps:
1) Import the following packages in your java file:***
import java.sql.*; import oracle.jdbc.driver.*; import oracle.sql.*;
2) Load and Register the JDBC driver:***
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
or you can use Class.forName("oracle.jdbc.driver.OracleDriver");
3) Connect to database:***
a) If you are using oracle oci driver,you have to use:
Connection conn = DriverManager.getConnection("jdbc:oracle:oci8:
@oracle.world", "root", "root");
where oracle.world is the TNSNAMES entry and root is the username and password.
b) If you are using oracle thin driver,you have to use:
Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@localhost:3306:roseindia",
"root", "root");
where localhost is the host,3306 is the port, roseindia is the database and root is the username and password.
4) Querying the database:**
a)create statement:
Statement st = conn.createStatement();
b)write query and execute the query:
ResultSet rs = st.executeQuery("SELECT * from student");
5) Close the statement,resultset and connection:**
rs.close(); st.close(); conn.close();
Try the following code:
import java.sql.*;
import oracle.sql.*;
import oracle.jdbc.driver.*;
public class OracleExample {
public static void main (String[] args) {
try{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection conn = DriverManager.getConnection("jdbc:oracle:thin: @localhost:3306:Oracle", "rose", "rose");
Statement st = conn.createStatement();
ResultSet rs = sql_stmt.executeQuery("SELECT * from student");
String str = "";
while (rs.next())
{
System.out.println(rset.getInt(1)+" "+ rs.getString(2)+" "+ rset.getFloat(3)+"\n";
}
rs.close();
st.close();
conn.close();
}
catch(Exception e){}
}
}