add

About Me

My photo
Oracle Apps - Techno Functional consultant

Friday, May 11

Setting up Oracle JDBC


The steps to enable your Java program to talk to Oracle database:
  1. Install Oracle and make sure it is running ok. (ie. you can connect to Oracle by sqlplus)
  2. Download the JDBC driver from Oracle at the following url.
    http://otn.oracle.com/software/tech/java/sqlj_jdbc/content.html
  3. Typically, the JDBC driver file you should download is named class12.zip.

    If you want to know the details of the JDBC drivers on the Oracle site. Here is some info.
    JDBC drivers can be classified into 4 types, ranging from pure Java driver to thin Java/heavy native driver. The class12.zip driver we chosen is the pure Java type. And for different type, there are different drivers for different Oracle versions and JDK versions. Pick the one that match your environment. I assume we are using Java 2, so we should use the class12.zip driver.
  4. Put this class12.zip file to your Java classpath.

    You should know how to do this. If not, follow the steps:
    For Windows 2000 (Windows 9x or XP should be similar):
    1. save class12.zip to C:\sjsu\cs157a\jdbc
    2. right click My Computer,
    3. choose Properties,
    4. click Advanced tab,
    5. click Environment Variables button,
    6. choose the variable CLASSPATH in the User variables table,
    7. click Edit button
    8. in the variable value text field, append ;C:\sjsu\cs157a\jdbc\classes12.zip
    9. if CLASSPATH is not present in the table, click Add button and type CLASSPATH in the variable name and type C:\sjsu\cs157a\jdbc\classes12.zip in the variable value box.

For Unix or Linux:
    1. save class12.zip to /usr/jdbc
    2. add the line setenv CLASSPATH $CLASSPATH:/usr/jdbc to your .login file.
    3. relogin to your shell
  1. Do a short simple test by issuing command in DOS or a shell:
    java oracle.jdbc.driver.OracleDriver
    You will get an error, but don't panic.

    If your error said:
    Exception in thread "main" java.lang.NoSuchMethodError: main
    Congradulation, you have setup JDBC driver correctly, despite what the error said.

    But if your error said:
    Exception in thread "main" java.lang.NoClassDefFoundError: oracle/jdbc/driver/OracleDrivera
    Your driver has not been setup correctly. Go back and review steps from 1 to 4.


  2. Done JDBC setup.
  3. Start to program and connect to Oracle through JDBC driver.
    Following is a simple test program to actually connect to Oracle and retrieve some data. (or download it here).
8.  8.            
9.  9.           import java.sql.*;
10.10.       import oracle.jdbc.driver.*;
11.11.       public class DbTest {
12.12.           public static void main (String args[]) throws Exception {
13.13.        
14.14.             // Load the Oracle JDBC driver
15.15.             DriverManager.registerDriver
16.16.                     (new oracle.jdbc.driver.OracleDriver());
17.17.        
18.18.             // connect through driver
19.19.             Connection conn = DriverManager.getConnection
20.20.                     ("jdbc:oracle:thin:@127.0.0.1:1521:ORCL","scott","tiger");
21.21.        
22.22.             // Create Oracle DatabaseMetaData object
23.23.             DatabaseMetaData meta = conn.getMetaData();
24.24.        
25.25.             // gets driver info:
26.26.             System.out.println("JDBC driver version is " + meta.getDriverVersion());
27.27.        
28.28.             // Create a statement
29.29.             Statement stmt = conn.createStatement();
30.30.        
31.31.             // Do the SQL "Hello World" thing
32.32.             ResultSet rset = stmt.executeQuery("SELECT TABLE_NAME FROM USER_TABLES");
33.33.        
34.34.             while (rset.next())
35.35.                System.out.println(rset.getString(1));
36.36.        
37.37.             // close the result set, the statement and disconnect
38.38.             rset.close();
39.39.             stmt.close();
40.40.             conn.close();
41.41.             System.out.println("Your JDBC installation is correct.");
42.42.          }
43.43.       }
  1. Compile and run the above DbTest. You should get the message Your JDBC installation is correct. If not, please see the following troubleshootings:
    1. If you get an error message similar to this: The system cannot find the file specified,
That means that you haven’t told the JDBC where you store your file. Assume that the path to reach your file(s) is C:\cs157aProject\, you have to reset your CLASSPATH as the following:  C:\sjsu\cs157a\jdbc\classes12.zip;C:\cs157aProject\  
Refer to step 4 to reset your CLASSPATH. If you still have problem of compiling your program, restart your computer.
Note: Once you setup the CLASSPATH, all your java programs have to store under the same directory to compile, no matter you use JDBC or not.
    1. If you get an error message similar to this:
Exception in thread "main" java.sql.SQLException: Io exception: Connection refused(DESCRIPTION=(TMP=)(VSNNUM=134238208)(ERR=12505)(ERROR_STACK=(ERROR=(CODE=12505)(EMFI=4))))
That means your database name in the code is not correct. Change the ORCL in your connection string in the DbTest.java to the correct database name. Recall that you had created your database name when installing Oracle. If you don't remember it, you could search your Oracle installation directory for a file called TNSNAMES.ORAand open it. Find the SID value, that is your database name.
    1. If you get the error message:

      Exception in thread "main" java.sql.SQLException: ORA-01017: invalid username/pa ssword; logon denied

      That obviously means your user name or password is not correct. scott/tiger is the default login to Oracle database, but you may have changed it while in Oracle installation.
    2. If you get this error:

      Exception in thread "main" java.sql.SQLException: Io exception: The Network Adap ter could not establish the connection

      That hints your Oracle TNS listener service may not have been started or your port number is not correct. Go to Windows Services console and start the Oracle TNS listener service if it is not already started. And check your Oracle database listening port number.

  1. Once the DbTest program runs correctly, you could start coding your own Java Database program. To make a good looking project, you should have knowledge of Java GUI programming such as Swing, AWT or Applet. Here we only get into details of the database programming portion.
    1. To connect through JDBC, the first thing you need is to load the JDBC driver to your program. Here is how you do it:
      DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
      This loaded driver enables you to make a connection to Oracle database.
    2. The next thing you would do is to make the actual connection:
      Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:ORCL","scott","tiger"); This tells the driver manager to create a connection to a database. The long parameter here is the essential part of connecting operation.
      1. The portion jdbc:oracle:thin instructs the driver manager to use the Oracle thin type jdbc driver, which is exactly the one we loaded in the previous step.
      2. The @127.0.0.1 indicates the database host that you are connecting to. Here I used the local machine IP address. You could change it to a remote machine name such as @sigma.mathcs.sjsu.edu, if that is the Oracle instance you want to connect to.
      3. The number 1521 is the port number of the Oracle database. The default when Oracle is installed is to listen to port #1521, but it is configurable, so make sure your code is using the right number.
      4. The second and third parameters are the username and password for your Oracle database.

    1. Once the connection is made, you may want to start issuing your SQL statement to Oracle within your code. You may then create a java.sql.Statement object by writing:
      Statement stmt = conn.createStatement();
    2. Using the Statement object, you can then construct your SQL statement and execute it. The result of a SQL statement will be assigned to a ResultSet object.
      String sqlString = "SELECT * FROM SUPPLIER";
      ResultSet rset = stmt.executeQuery(sqlString);
    3. If your SQL statement runs successfully, you will be able to walk through the obtained ResultSet object to get result details. Here is one example:
6.  6.                 int numCols = 4; // there are 4 columns in SUPPLIER table
7.  7.                 while (rset.next()) { // walk through each row
8.  8.                     for (int i = 1; i<=numCols; i++) {
9.  9.                         System.out.println(rset.getString(i) + " "); // print each columen
10.10.                 }
11.11.                  System.out.println();
} 
  1. A complete database demo with GUI can be downloaded here:
    JdbcDemo.zip



No comments: