JDBC offers a database independent interface to connect to various SQL databases. It's similar to Perl DBI.
A typical JDBC Program looks like this
import java.sql.*;
public class connect {
public static void main(String args[]) {
String url = "jdbc:oracle:thin:@oracle:1521:cen3031";
// Load the oracle driver
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch (Exception e) {
System.out.println("Failed to load oracle driver");
System.out.println(e.toString());
System.exit(1);
}
try {
// Make a connection handle to the database
Connection con = DriverManager.getConnection(url, "ppadala", "******");
// Prepare and execute a statement
Statement st = con.createStatement();
ResultSet result = st.executeQuery("select * from oraclehw");
System.out.println("Results");
// Display the results
while(result.next()) {
System.out.println("name = " + result.getString(1));
System.out.println("email = " + result.getString(2));
}
// Release the resources for connection
st.close();
con.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
|
The comments pretty much explain the program. It follows the same pattern described in the Database Programming tutorial.
To compile the program, set ORACLE_HOME and CLASSPATH with
source /usr/local/etc/ora.csh
setenv CLASSPATH ${CLASSPATH}:${ORACLE_HOME}/jdbc/lib/classes12.zip
Compile the program with javac
javac <java source>
Execute the class file as
java <class name>
If you get an error like
rain% java connect
Failed to load oracle driver
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
Make sure that you set the classpath properly. Execute these programs
on CISE main servers rain and sand only.
rain:19% java connect Results ------- name = rte email = rt name = robert email = rmc@cise.ufl.edu name = banana email = abc@banana.com name = Pradeep Padala email = abc@bbc.com name = banana email = abc@banana.com |