6
Setting up Oracle JDBC  Authors: Lichu Dang, Lixin Yu The steps to enable your Java program to talk to Oracle database: 1. Ins tal l Ora cle a nd mak e sur e it is r unni ng ok. (ie. you can connect to Oracle by sqlplus) 2. Downlo ad the JDBC drive r from Oracl e at t he fol lowing url. http://otn.oracle.com/software/tech/java/sqlj_jdbc/content.html 3. Typic ally , the J DBC dr iver f ile y ou sh ould do wnload is na med 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 class 12.zip file to y our J ava c lassp ath. You should know how to do this. If not, follow the steps: For Windows 2000 (Windows 9x or XP should be similar): 1. save clas s12.zi p to C:\s jsu \cs 157a \jd bc 2. right click  My Computer, 3. choose Properties , 4. click  Advanced tab, 5. click  Environment Variables button, 6. choose t he var ia bl e CLASSPATH in the User variables table, 7. click  Edit button 8. in the variable va lue text f iel d, append  ;C:\sjsu\cs157a\jdbc\classes12.zip  9. if CLASSP ATH i s not presen t in the t able, 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: 10. save class 12.zip to /usr /jdbc

Setting Up Jdbc & Odbc

Embed Size (px)

Citation preview

Page 1: Setting Up Jdbc & Odbc

8/8/2019 Setting Up Jdbc & Odbc

http://slidepdf.com/reader/full/setting-up-jdbc-odbc 1/6

Setting up Oracle JDBC

 Authors: Lichu Dang, Lixin Yu

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:

10. save class12.zip to /usr/jdbc

Page 2: Setting Up Jdbc & Odbc

8/8/2019 Setting Up Jdbc & Odbc

http://slidepdf.com/reader/full/setting-up-jdbc-odbc 2/6

11. add the line setenv CLASSPATH $CLASSPATH:/usr/jdbc to your .login file.

12. relogin to your shell

2. 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.

3. Done JDBC setup.

4. 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).5.6.   import java.sql.*;7.   import oracle.jdbc.driver.*;8.  public class DbTest {9. public static void main (String args[]) throws Exception {10.

11. // Load the Oracle JDBC driver12. DriverManager.registerDriver13. (new oracle.jdbc.driver.OracleDriver());14.  

15. // connect through driver16. Connection conn = DriverManager.getConnection17. ("jdbc:oracle:thin:@127.0.0.1:1521:ORCL","scott","tiger");18.19. // Create Oracle DatabaseMetaData object20. DatabaseMetaData meta = conn.getMetaData();21. // gets driver info:22. System.out.println("JDBC driver version is " +

meta.getDriverVersion());23.  

24.   // Create a statement25. Statement stmt = conn.createStatement();26.27.   // Do the SQL "Hello World" thing28. ResultSet rset = stmt.executeQuery("SELECT TABLE_NAME FROM

USER_TABLES");29.30. while (rset.next())31. System.out.println(rset.getString(1));

Page 3: Setting Up Jdbc & Odbc

8/8/2019 Setting Up Jdbc & Odbc

http://slidepdf.com/reader/full/setting-up-jdbc-odbc 3/6

32.33.   // close the result set, the statement and disconnect34.   rset.close();35.   stmt.close();36.   conn.close();37. System.out.println("Your JDBC installation is correct.");38. }39.   }

40. 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. Assumethat 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.

2. 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 calledTNSNAMES.ORA and open it. Find the SID value, that is your database name.

3. 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 thedefault login to Oracle database, but you may have changed it while in Oracle

installation.

4. If you get this error:

 Exception in thread "main" java.sql.SQLException: Io exception: The Network 

 Adap ter could not establish the connection

Page 4: Setting Up Jdbc & Odbc

8/8/2019 Setting Up Jdbc & Odbc

http://slidepdf.com/reader/full/setting-up-jdbc-odbc 4/6

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 OracleTNS listener service if it is not already started. And check your Oracle database

listening port number.

41. 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 theOracle 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 Oracleinstance you want to connect to.

3. The number 1521 is the port number of the Oracle database. The defaultwhen 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.

3. 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 bywriting:

Statement stmt = conn.createStatement(); 

4. 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);

Page 5: Setting Up Jdbc & Odbc

8/8/2019 Setting Up Jdbc & Odbc

http://slidepdf.com/reader/full/setting-up-jdbc-odbc 5/6

5. 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.  int numCols = 4; // there are 4 columns in SUPPLIER table7.  while (rset.next())8. {9.   // walk through each row

10. for (int i = 1; i<=numCols; i++)11. {12. // print each columen13. System.out.println(rset.getString(i) + " ");

14. }15. System.out.println();

}

42. A complete database demo with GUI can be downloaded here:

JdbcDemo.zip

Setting up a data source (ODBC)

You need to create a data source to be able to allow C to talk to Oracle

• Select Microsoft ODBC administrator from Oracle/Network Adminstration 

• Data source typeso Select the user DSN tab if the data source will only be used from your PC for the

logged on username (Typically, entries in this tab are added by applications that

are installed locally and that use a data source, such as Microsoft Office) else

select the System DSN tab.o The System DSN tab allows you to configure a specific data source to a client-

server database. Using the System DSN tab to configure a connection will write

an entry for that connection in the registry in

 HKEY_LOCAL_MACHINE\Software\ODBC\ODBC.INI\ODBC Data Sources.The advantage of this is faster access, since it is in the registry. The disadvantage

is that it will have to be created on each local machine.o The File DSN tab does the same thing as the System DSN tab, but the File DSN

tab will create a file stored on the local server with the extension .dsn on the local

drive in the folder at C:\Program Files\Common Files\ODBC\Data Sources. The

advantage of this approach is that the file can be easily copied to other machines.

• Press Add

• You will be asked which driver to use. Choose Oracle ODBC Driver NOT Microsoft ODBC for Oracle since this is the driver that you have just installed and will not cause problems such as described in ODBC Problems 

• Choose a data source name- can be the same as the data source service that you specifiedabove eg cs157a or perhaps the username to be used

• Choose a description eg cs157a• Give a data source service name. This must relate to the definition in the tnsnames.ora

file eg sjsu

• Give the default username for that datasource

• Click OK 

Page 6: Setting Up Jdbc & Odbc

8/8/2019 Setting Up Jdbc & Odbc

http://slidepdf.com/reader/full/setting-up-jdbc-odbc 6/6

• You can now test the data source by using ODBC test from Oracle/Network  Adminstration 

• Press Connect

• Choose a data source from the Machine Data Source tab

• Give the passwd for the given service name and username

Type some SQL eg select table_name from user_tables • Press the Execute button and hopefully some data will appear 

• If something goes wrong, test the service name by typing tnsping xxx on the Command

Prompt found in Program /Accessories on the Start menu to check the database is up

• The Connection Pooling tab allows you to enable and configure connection pooling for a

specified driver. Connection pooling uses a connection to a data source from a pool of 

connections, so that a connection does not have to be reestablished each time you access

the data source. Unless you are having trouble establishing or maintaining a connection,you probably will not use this tab. Connection pooling timeout is set to 120 second by

default.