Making Connection to Oracle Database System with Java
[info]You may need to Java and Eclipse Configured and Installed. If not please click here for instructions to install the JDK and download Eclipse[/info]
[info] If you don’t have Oracle XE installed, Follow this tutorial for how to Get started to learn Oracle[/info]
Oracle Database Creation
1 Open your Apex for Oracle: Click on Start -> All Programs -> Oracle database 11g Express Edition -> Go to Database Home Page
2 Visit the SQL Command : SQL -> SQL Command
3 Execute the following SQL to create a table called friends.
create table friends( fname VARCHAR2(100), lname VARCHAR2(100) )
Java Connection to Oracle
1 Create a new Java Project called : HelloOracle.
2 Create a new Java Class named Hello under the project HelloOracle.
3 Type the following code for the class Hello
import java.io.*; import java.sql.*; import java.util.*; public class Hello { public static void main(String [] args){ try{ String userName = "system"; String password = "YourPassword"; String url = "jdbc:oracle:thin:@localhost:1521:xe"; Class.forName ("oracle.jdbc.OracleDriver").newInstance (); Connection conn = DriverManager.getConnection (url, userName, password); //Inserting data: PreparedStatement pstmt = conn.prepareStatement("insert into friends (fname,lname) values ('Imed' , 'Bouch')"); pstmt.executeUpdate(); pstmt = conn.prepareStatement("insert into friends (fname,lname) values ('Asma' , 'Bouch')"); pstmt.executeUpdate(); //Searching for Data. pstmt = conn.prepareStatement("select * from friends"); ResultSet rs = pstmt.executeQuery(); while(rs.next()){ String fname= rs.getString("fname"); String lname= rs.getString("lname"); System.out.println(fname+"\t\t\t"+lname); } rs.close(); pstmt.close(); }catch(Exception e){ e.printStackTrace(); } } }
4 Download the JDBC Driver for Oracle from the link below.
[info]Click here to download the JDBC Driver : ojdbc6.jar [/info]
5 Within Eclipse, click Run -> Run Configurations.
6 Make sure you select your project from the left side panel. Otherwise, DOUBLE click on Java Application to appear.
7 Click on Classpath , then Click on User Entries , then click on Add External Jars. Locate the OJDBC6.jar file and add it.
8 That’s it. Apply and Run your project.
[success]In case you are not using Eclipse, To run your project use the -cp argument. For example :
java -cp ojdbc.jar Main[/success]