Java Database Connectivity (JDBC) is an API for the Java programming language that defines how a client may access a database. It provides methods for querying and updating data in a database. JDBC is oriented towards relational databases.
This page describes how to use JDBC to connect to the UB Academic Oracle Service (AOS).
- Login to any 64-bit student Linux system.
- Set C Oracle environment variables contained in coraenv.sh:
% source /util/oracle/coraenv.sh
This example uses connection pooling.
A full working version of this code is attached as DBTest.java, below. Highlights:
- Write a foo.java file that includes code to establish an Oracle connection:
- Import Oracle drivers:
import oracle.jdbc.pool.OracleDataSource;
- Establish a connection to the Oracle instance:
OracleDataSource ods = new OracleDataSource();
ods.setUser(user);
ods.setPassword(pass);
ods.setURL ("jdbc:oracle:thin:@aos.acsu.buffalo.edu:1521/aos.buffalo.edu");
Connection conn = ods.getConnection();
This example does not use connection pooling.
A full working version of this code is attached as JDBCTest02.java, below. Highlights:
- Oracle's JDBC driver is located in a Java package called oracle. In order to load the JDBC driver in your Java programs, include the line:
Class.forName ("oracle.jdbc.driver.OracleDriver");
-
However, if there is a problem, the above statement will throw an exception, so it's good programming practice to catch this exception within a try block:
try {
Class.forName ("oracle.jdbc.driver.OracleDriver");
}
catch (ClassNotFoundException e){
System.out.println("Could not load the JDBC driver. Check your CLASSPATH.");
System.exit(0);
}
- Use this connection string syntax to connect to AOS:
Connection con = DriverManager.getConnection("jdbc:oracle:thin:"+user+"/"+passwd+"@aos.acsu.buffalo.edu:1521/aos.buffalo.edu");
- Compile foo.java:
% javac foo.java
- Run compiled Java code:
% java foo
- http://en.wikipedia.org/wiki/JDBC
- http://java.sun.com/javase/technologies/database/
- http://www.oracle.com/technology/tech/java/sqlj_jdbc/index.html
- http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/index.html
- http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/htdocs/jdb...